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 |
|---|---|---|---|---|---|
Potree.TranslationTool = function(camera) {
THREE.Object3D.call( this );
var scope = this;
this.camera = camera;
this.geometry = new THREE.Geometry();
this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
this.STATE = {
DEFAULT: 0,
TRANSLATE_X: 1,
TRANSLATE_Y: 2,
TRANSLATE_Z: 3
};
this.parts = {
ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X},
ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y},
ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z}
}
this.translateStart;
this.state = this.STATE.DEFAULT;
this.highlighted;
this.targets;
this.build = function(){
var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color);
arrowX.rotation.z = -Math.PI/2;
var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color);
var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color);
arrowZ.rotation.x = -Math.PI/2;
scope.add(arrowX);
scope.add(arrowY);
scope.add(arrowZ);
var boxXY = scope.createBox(new THREE.Color( 0xffff00 ));
boxXY.scale.z = 0.02;
boxXY.position.set(0.5, 0.5, 0);
var boxXZ = scope.createBox(new THREE.Color( 0xff00ff ));
boxXZ.scale.y = 0.02;
boxXZ.position.set(0.5, 0, -0.5);
var boxYZ = scope.createBox(new THREE.Color( 0x00ffff ));
boxYZ.scale.x = 0.02;
boxYZ.position.set(0, 0.5, -0.5);
scope.add(boxXY);
scope.add(boxXZ);
scope.add(boxYZ);
scope.parts.ARROW_X.object = arrowX;
scope.parts.ARROW_Y.object = arrowY;
scope.parts.ARROW_Z.object = arrowZ;
scope.scale.multiplyScalar(5);
};
this.createBox = function(color){
var boxGeometry = new THREE.BoxGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5});
var box = new THREE.Mesh(boxGeometry, boxMaterial);
return box;
};
this.createArrow = function(partID, color){
var material = new THREE.MeshBasicMaterial({color: color});
var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false);
var shaftMatterial = material;
var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial);
shaft.position.y = 1.5;
var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false);
var headMaterial = material;
var head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 3;
var arrow = new THREE.Object3D();
arrow.add(shaft);
arrow.add(head);
arrow.partID = partID;
arrow.material = material;
return arrow;
};
this.setHighlighted = function(partID){
if(partID === undefined){
if(scope.highlighted){
scope.highlighted.object.material.color = scope.highlighted.color;
scope.highlighted = undefined;
}
return;
}else if(scope.highlighted !== undefined && scope.highlighted !== partID){
scope.highlighted.object.material.color = scope.highlighted.color;
}
scope.highlighted = partID;
partID.object.material.color = new THREE.Color(0xffff00);
}
this.getHoveredObject = function(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
vector.unproject(scope.camera);
var raycaster = new THREE.Raycaster();
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var intersections = raycaster.intersectObject(scope, true);
if(intersections.length === 0){
scope.setHighlighted(undefined);
return undefined;
}
var I = intersections[0];
var partID = I.object.parent.partID;
return partID;
}
this.onMouseMove = function(event){
var mouse = event.normalizedPosition;
if(scope.state === scope.STATE.DEFAULT){
scope.setHighlighted(scope.getHoveredObject(mouse));
}else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){
var origin = scope.start.lineStart.clone();
var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart);
direction.normalize();
var mousePoint = new THREE.Vector3(mouse.x, mouse.y);
var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction);
var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin);
pointOnLine.unproject(scope.camera);
var diff = pointOnLine.clone().sub(scope.position);
scope.position.copy(pointOnLine);
for(var i = 0; i < scope.targets.length; i++){
var target = scope.targets[0];
target.position.add(diff);
}
event.signal.halt();
}
};
this.onMouseDown = function(event){
if(scope.state === scope.STATE.DEFAULT){
var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera);
if(hoveredObject){
scope.state = hoveredObject.state;
var lineStart = scope.position.clone();
var lineEnd;
if(scope.state === scope.STATE.TRANSLATE_X){
lineEnd = scope.position.clone();
lineEnd.x += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Y){
lineEnd = scope.position.clone();
lineEnd.y += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Z){
lineEnd = scope.position.clone();
lineEnd.z -= 2;
}
lineStart.project(scope.camera);
lineEnd.project(scope.camera);
scope.start = {
mouse: event.normalizedPosition,
lineStart: lineStart,
lineEnd: lineEnd
};
event.signal.halt();
}
}
};
this.onMouseUp = function(event){
scope.setHighlighted();
scope.state = scope.STATE.DEFAULT;
};
this.setTargets = function(targets){
scope.targets = targets;
if(scope.targets.length === 0){
return;
}
//TODO calculate centroid of all targets
var centroid = targets[0].position.clone();
//for(var i = 0; i < targets.length; i++){
// var target = targets[i];
//}
scope.position.copy(centroid);
}
this.build();
};
Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );
| idunshee/Portfolio | Project/WPC/WPC_Viewer/src/utils/TranslationTool.js | JavaScript | apache-2.0 | 6,194 |
package bwhatsapp
import (
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)
type ProfilePicInfo struct {
URL string `json:"eurl"`
Tag string `json:"tag"`
Status int16 `json:"status"`
}
func qrFromTerminal(invert bool) chan string {
qr := make(chan string)
go func() {
terminal := qrcodeTerminal.New()
if invert {
terminal = qrcodeTerminal.New2(qrcodeTerminal.ConsoleColors.BrightWhite, qrcodeTerminal.ConsoleColors.BrightBlack, qrcodeTerminal.QRCodeRecoveryLevels.Medium)
}
terminal.Get(<-qr).Print()
}()
return qr
}
func (b *Bwhatsapp) readSession() (whatsapp.Session, error) {
session := whatsapp.Session{}
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
return session, errors.New("if you won't set SessionFile then you will need to scan QR code on every restart")
}
file, err := os.Open(sessionFile)
if err != nil {
return session, err
}
defer file.Close()
decoder := gob.NewDecoder(file)
return session, decoder.Decode(&session)
}
func (b *Bwhatsapp) writeSession(session whatsapp.Session) error {
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
// we already sent a warning while starting the bridge, so let's be quiet here
return nil
}
file, err := os.Create(sessionFile)
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
return encoder.Encode(session)
}
func (b *Bwhatsapp) restoreSession() (*whatsapp.Session, error) {
session, err := b.readSession()
if err != nil {
b.Log.Warn(err.Error())
}
b.Log.Debugln("Restoring WhatsApp session..")
session, err = b.conn.RestoreWithSession(session)
if err != nil {
// restore session connection timed out (I couldn't get over it without logging in again)
return nil, errors.New("failed to restore session: " + err.Error())
}
b.Log.Debugln("Session restored successfully!")
return &session, nil
}
func (b *Bwhatsapp) getSenderName(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
if sender.Name != "" {
return sender.Name
}
// if user is not in phone contacts
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
// users can change it in their WhatsApp settings -> profile -> click on Avatar
if sender.Notify != "" {
return sender.Notify
}
if sender.Short != "" {
return sender.Short
}
}
// try to reload this contact
_, err := b.conn.Contacts()
if err != nil {
b.Log.Errorf("error on update of contacts: %v", err)
}
if contact, exists := b.conn.Store.Contacts[senderJid]; exists {
// Add it to the user map
b.users[senderJid] = contact
if contact.Name != "" {
return contact.Name
}
// if user is not in phone contacts
// same as above
return contact.Notify
}
return ""
}
func (b *Bwhatsapp) getSenderNotify(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
return sender.Notify
}
return ""
}
func (b *Bwhatsapp) GetProfilePicThumb(jid string) (*ProfilePicInfo, error) {
data, err := b.conn.GetProfilePicThumb(jid)
if err != nil {
return nil, fmt.Errorf("failed to get avatar: %v", err)
}
content := <-data
info := &ProfilePicInfo{}
err = json.Unmarshal([]byte(content), info)
if err != nil {
return info, fmt.Errorf("failed to unmarshal avatar info: %v", err)
}
return info, nil
}
func isGroupJid(identifier string) bool {
return strings.HasSuffix(identifier, "@g.us") ||
strings.HasSuffix(identifier, "@temp") ||
strings.HasSuffix(identifier, "@broadcast")
}
| 42wim/matterbridge | bridge/whatsapp/helpers.go | GO | apache-2.0 | 3,689 |
'use strict';
var consoleBaseUrl = window.location.href;
consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf("/console"));
consoleBaseUrl = consoleBaseUrl + "/console";
var configUrl = consoleBaseUrl + "/config";
var auth = {};
var resourceBundle;
var locale = 'en';
var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'angularTreeview', 'pascalprecht.translate', 'ngCookies', 'ngSanitize', 'ui.ace']);
var resourceRequests = 0;
var loadingTimer = -1;
angular.element(document).ready(function () {
var keycloakAuth = new Keycloak(configUrl);
function whoAmI(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + "/whoami", true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'bearer ' + keycloakAuth.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success(data);
} else {
error();
}
}
}
req.send();
}
function loadResourceBundle(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + '/messages.json?lang=' + locale, true);
req.setRequestHeader('Accept', 'application/json');
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success && success(data);
} else {
error && error();
}
}
}
req.send();
}
function hasAnyAccess(user) {
return user && user['realm_access'];
}
keycloakAuth.onAuthLogout = function() {
location.reload();
}
keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
auth.authz = keycloakAuth;
if (auth.authz.idTokenParsed.locale) {
locale = auth.authz.idTokenParsed.locale;
}
auth.refreshPermissions = function(success, error) {
whoAmI(function(data) {
auth.user = data;
auth.loggedIn = true;
auth.hasAnyAccess = hasAnyAccess(data);
success();
}, function() {
error();
});
};
loadResourceBundle(function(data) {
resourceBundle = data;
auth.refreshPermissions(function () {
module.factory('Auth', function () {
return auth;
});
var injector = angular.bootstrap(document, ["keycloak"]);
injector.get('$translate')('consoleTitle').then(function (consoleTitle) {
document.title = consoleTitle;
});
});
});
}).error(function () {
window.location.reload();
});
});
module.factory('authInterceptor', function($q, Auth) {
return {
request: function (config) {
if (!config.url.match(/.html$/)) {
var deferred = $q.defer();
if (Auth.authz.token) {
Auth.authz.updateToken(5).success(function () {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + Auth.authz.token;
deferred.resolve(config);
}).error(function () {
location.reload();
});
}
return deferred.promise;
} else {
return config;
}
}
};
});
module.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
$translateProvider.preferredLanguage(locale);
$translateProvider.translations(locale, resourceBundle);
}]);
module.config([ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/create/realm', {
templateUrl : resourceUrl + '/partials/realm-create.html',
resolve : {
},
controller : 'RealmCreateCtrl'
})
.when('/realms/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/login-settings', {
templateUrl : resourceUrl + '/partials/realm-login-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmLoginSettingsCtrl'
})
.when('/realms/:realm/theme-settings', {
templateUrl : resourceUrl + '/partials/realm-theme-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmThemeCtrl'
})
.when('/realms/:realm/cache-settings', {
templateUrl : resourceUrl + '/partials/realm-cache-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmCacheCtrl'
})
.when('/realms', {
templateUrl : resourceUrl + '/partials/realm-list.html',
controller : 'RealmListCtrl'
})
.when('/realms/:realm/token-settings', {
templateUrl : resourceUrl + '/partials/realm-tokens.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmTokenDetailCtrl'
})
.when('/realms/:realm/client-initial-access', {
templateUrl : resourceUrl + '/partials/client-initial-access.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientInitialAccess : function(ClientInitialAccessLoader) {
return ClientInitialAccessLoader();
},
clientRegTrustedHosts : function(ClientRegistrationTrustedHostListLoader) {
return ClientRegistrationTrustedHostListLoader();
}
},
controller : 'ClientInitialAccessCtrl'
})
.when('/realms/:realm/client-initial-access/create', {
templateUrl : resourceUrl + '/partials/client-initial-access-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'ClientInitialAccessCreateCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/create', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function() {
return {};
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/:hostname', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function(ClientRegistrationTrustedHostLoader) {
return ClientRegistrationTrustedHostLoader();
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/keys-settings', {
templateUrl : resourceUrl + '/partials/realm-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmKeysDetailCtrl'
})
.when('/realms/:realm/identity-provider-settings', {
templateUrl : resourceUrl + '/partials/realm-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return {};
},
authFlows : function(AuthenticationFlowsLoader) {
return {};
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/create/identity-provider/:realm/:provider_id', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return new IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias/export', {
templateUrl : resourceUrl + '/partials/realm-identity-provider-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
}
},
controller : 'RealmIdentityProviderExportCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mappers : function(IdentityProviderMappersLoader) {
return IdentityProviderMappersLoader();
}
},
controller : 'IdentityProviderMapperListCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mapper : function(IdentityProviderMapperLoader) {
return IdentityProviderMapperLoader();
}
},
controller : 'IdentityProviderMapperCtrl'
})
.when('/create/identity-provider-mappers/:realm/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
}
},
controller : 'IdentityProviderMapperCreateCtrl'
})
.when('/realms/:realm/default-roles', {
templateUrl : resourceUrl + '/partials/realm-default-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RealmDefaultRolesCtrl'
})
.when('/realms/:realm/smtp-settings', {
templateUrl : resourceUrl + '/partials/realm-smtp.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmSMTPSettingsCtrl'
})
.when('/realms/:realm/events', {
templateUrl : resourceUrl + '/partials/realm-events.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmEventsCtrl'
})
.when('/realms/:realm/admin-events', {
templateUrl : resourceUrl + '/partials/realm-events-admin.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmAdminEventsCtrl'
})
.when('/realms/:realm/events-settings', {
templateUrl : resourceUrl + '/partials/realm-events-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
eventsConfig : function(RealmEventsConfigLoader) {
return RealmEventsConfigLoader();
}
},
controller : 'RealmEventsConfigCtrl'
})
.when('/realms/:realm/partial-import', {
templateUrl : resourceUrl + '/partials/partial-import.html',
resolve : {
resourceName : function() { return 'users'},
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmImportCtrl'
})
.when('/create/user/:realm', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function() {
return {};
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-attributes', {
templateUrl : resourceUrl + '/partials/user-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-credentials', {
templateUrl : resourceUrl + '/partials/user-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserCredentialsCtrl'
})
.when('/realms/:realm/users/:user/role-mappings', {
templateUrl : resourceUrl + '/partials/role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/realms/:realm/users/:user/groups', {
templateUrl : resourceUrl + '/partials/user-group-membership.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'UserGroupMembershipCtrl'
})
.when('/realms/:realm/users/:user/sessions', {
templateUrl : resourceUrl + '/partials/user-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
sessions : function(UserSessionsLoader) {
return UserSessionsLoader();
}
},
controller : 'UserSessionsCtrl'
})
.when('/realms/:realm/users/:user/federated-identity', {
templateUrl : resourceUrl + '/partials/user-federated-identity-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityCtrl'
})
.when('/create/federated-identity/:realm/:user', {
templateUrl : resourceUrl + '/partials/user-federated-identity-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityAddCtrl'
})
.when('/realms/:realm/users/:user/consents', {
templateUrl : resourceUrl + '/partials/user-consents.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
userConsents : function(UserConsentsLoader) {
return UserConsentsLoader();
}
},
controller : 'UserConsentsCtrl'
})
.when('/realms/:realm/users/:user/offline-sessions/:client', {
templateUrl : resourceUrl + '/partials/user-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessions : function(UserOfflineSessionsLoader) {
return UserOfflineSessionsLoader();
}
},
controller : 'UserOfflineSessionsCtrl'
})
.when('/realms/:realm/users', {
templateUrl : resourceUrl + '/partials/user-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'UserListCtrl'
})
.when('/create/role/:realm', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles/:role', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function(RoleLoader) {
return RoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles', {
templateUrl : resourceUrl + '/partials/role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RoleListCtrl'
})
.when('/realms/:realm/groups', {
templateUrl : resourceUrl + '/partials/group-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'GroupListCtrl'
})
.when('/create/group/:realm/parent/:parentId', {
templateUrl : resourceUrl + '/partials/create-group.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
parentId : function($route) {
return $route.current.params.parentId;
}
},
controller : 'GroupCreateCtrl'
})
.when('/realms/:realm/groups/:group', {
templateUrl : resourceUrl + '/partials/group-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/attributes', {
templateUrl : resourceUrl + '/partials/group-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/members', {
templateUrl : resourceUrl + '/partials/group-members.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupMembersCtrl'
})
.when('/realms/:realm/groups/:group/role-mappings', {
templateUrl : resourceUrl + '/partials/group-role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'GroupRoleMappingCtrl'
})
.when('/realms/:realm/default-groups', {
templateUrl : resourceUrl + '/partials/default-groups.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'DefaultGroupsCtrl'
})
.when('/create/role/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/roles/:role', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function(ClientRoleLoader) {
return ClientRoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientProtocolMapperListCtrl'
})
.when('/realms/:realm/clients/:client/add-mappers', {
templateUrl : resourceUrl + '/partials/client-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'AddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/clients/:client/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientProtocolMapperLoader) {
return ClientProtocolMapperLoader();
}
},
controller : 'ClientProtocolMapperCtrl'
})
.when('/create/client/:realm/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientProtocolMapperCreateCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateProtocolMapperListCtrl'
})
.when('/realms/:realm/client-templates/:template/add-mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateAddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientTemplateProtocolMapperLoader) {
return ClientTemplateProtocolMapperLoader();
}
},
controller : 'ClientTemplateProtocolMapperCtrl'
})
.when('/create/client-template/:realm/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
}
},
controller : 'ClientTemplateProtocolMapperCreateCtrl'
})
.when('/realms/:realm/clients/:client/sessions', {
templateUrl : resourceUrl + '/partials/client-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
sessionCount : function(ClientSessionCountLoader) {
return ClientSessionCountLoader();
}
},
controller : 'ClientSessionsCtrl'
})
.when('/realms/:realm/clients/:client/offline-access', {
templateUrl : resourceUrl + '/partials/client-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessionCount : function(ClientOfflineSessionCountLoader) {
return ClientOfflineSessionCountLoader();
}
},
controller : 'ClientOfflineSessionsCtrl'
})
.when('/realms/:realm/clients/:client/credentials', {
templateUrl : resourceUrl + '/partials/client-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
},
clientConfigProperties: function(PerClientAuthenticationConfigDescriptionLoader) {
return PerClientAuthenticationConfigDescriptionLoader();
}
},
controller : 'ClientCredentialsCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/identity-provider', {
templateUrl : resourceUrl + '/partials/client-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientIdentityProviderCtrl'
})
.when('/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringCtrl'
})
.when('/register-node/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/clustering/:node', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/saml/keys', {
templateUrl : resourceUrl + '/partials/client-saml-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientSamlKeyCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/roles', {
templateUrl : resourceUrl + '/partials/client-role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
roles : function(ClientRoleListLoader) {
return ClientRoleListLoader();
}
},
controller : 'ClientRoleListCtrl'
})
.when('/realms/:realm/clients/:client/revocation', {
templateUrl : resourceUrl + '/partials/client-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientRevocationCtrl'
})
.when('/realms/:realm/clients/:client/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientScopeMappingCtrl'
})
.when('/realms/:realm/clients/:client/installation', {
templateUrl : resourceUrl + '/partials/client-installation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientInstallationCtrl'
})
.when('/realms/:realm/clients/:client/service-account-roles', {
templateUrl : resourceUrl + '/partials/client-service-account-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(ClientServiceAccountUserLoader) {
return ClientServiceAccountUserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/create/client/:realm', {
templateUrl : resourceUrl + '/partials/create-client.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'CreateClientCtrl'
})
.when('/realms/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientDetailCtrl'
})
.when('/create/client-template/:realm', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-template-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientTemplateScopeMappingCtrl'
})
.when('/realms/:realm/clients', {
templateUrl : resourceUrl + '/partials/client-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientListCtrl'
})
.when('/realms/:realm/client-templates', {
templateUrl : resourceUrl + '/partials/client-template-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateListCtrl'
})
.when('/import/client/:realm', {
templateUrl : resourceUrl + '/partials/client-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientImportCtrl'
})
.when('/', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'HomeCtrl'
})
.when('/mocks/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail_mock.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/sessions/revocation', {
templateUrl : resourceUrl + '/partials/session-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmRevocationCtrl'
})
.when('/realms/:realm/sessions/realm', {
templateUrl : resourceUrl + '/partials/session-realm.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
stats : function(RealmClientSessionStatsLoader) {
return RealmClientSessionStatsLoader();
}
},
controller : 'RealmSessionStatsCtrl'
})
.when('/create/user-storage/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-storage/providers/:provider/:componentId', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(ComponentLoader) {
return ComponentLoader();
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-federation', {
templateUrl : resourceUrl + '/partials/user-federation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'UserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/ldap/:instance', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
}
},
controller : 'LDAPCtrl'
})
.when('/create/user-federation/:realm/providers/ldap', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
}
},
controller : 'LDAPCtrl'
})
.when('/realms/:realm/user-federation/providers/kerberos/:instance', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/kerberos', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mappers : function(UserFederationMappersLoader) {
return UserFederationMappersLoader();
}
},
controller : 'UserFederationMapperListCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mapper : function(UserFederationMapperLoader) {
return UserFederationMapperLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCtrl'
})
.when('/create/user-federation-mappers/:realm/:provider/:instance', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCreateCtrl'
})
.when('/realms/:realm/defense/headers', {
templateUrl : resourceUrl + '/partials/defense-headers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'DefenseHeadersCtrl'
})
.when('/realms/:realm/defense/brute-force', {
templateUrl : resourceUrl + '/partials/brute-force.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmBruteForceCtrl'
})
.when('/realms/:realm/protocols', {
templateUrl : resourceUrl + '/partials/protocol-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ProtocolListCtrl'
})
.when('/realms/:realm/authentication/flows', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function() {
return null;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flow-bindings', {
templateUrl : resourceUrl + '/partials/authentication-flow-bindings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmFlowBindingCtrl'
})
.when('/realms/:realm/authentication/flows/:flow', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function($route) {
return $route.current.params.flow;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formActionProviders : function(AuthenticationFormActionProvidersLoader) {
return AuthenticationFormActionProvidersLoader();
},
authenticatorProviders : function(AuthenticatorProvidersLoader) {
return AuthenticatorProvidersLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
}
},
controller : 'CreateExecutionCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/flow/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-flow-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formProviders : function(AuthenticationFormProvidersLoader) {
return AuthenticationFormProvidersLoader();
}
},
controller : 'CreateExecutionFlowCtrl'
})
.when('/realms/:realm/authentication/create/flow', {
templateUrl : resourceUrl + '/partials/create-flow.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'CreateFlowCtrl'
})
.when('/realms/:realm/authentication/required-actions', {
templateUrl : resourceUrl + '/partials/required-actions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
unregisteredRequiredActions : function(UnregisteredRequiredActionsListLoader) {
return UnregisteredRequiredActionsListLoader();
}
},
controller : 'RequiredActionsCtrl'
})
.when('/realms/:realm/authentication/password-policy', {
templateUrl : resourceUrl + '/partials/password-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmPasswordPolicyCtrl'
})
.when('/realms/:realm/authentication/otp-policy', {
templateUrl : resourceUrl + '/partials/otp-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmOtpPolicyCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/config/:provider/:config', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
config : function(AuthenticationConfigLoader) {
return AuthenticationConfigLoader();
}
},
controller : 'AuthenticationConfigCtrl'
})
.when('/create/authentication/:realm/flows/:flow/execution/:executionId/provider/:provider', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
execution : function(ExecutionIdLoader) {
return ExecutionIdLoader();
}
},
controller : 'AuthenticationConfigCreateCtrl'
})
.when('/server-info', {
templateUrl : resourceUrl + '/partials/server-info.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/server-info/providers', {
templateUrl : resourceUrl + '/partials/server-info-providers.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/logout', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'LogoutCtrl'
})
.when('/notfound', {
templateUrl : resourceUrl + '/partials/notfound.html'
})
.when('/forbidden', {
templateUrl : resourceUrl + '/partials/forbidden.html'
})
.otherwise({
templateUrl : resourceUrl + '/partials/pagenotfound.html'
});
} ]);
module.config(function($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
var spinnerFunction = function(data, headersGetter) {
if (resourceRequests == 0) {
loadingTimer = window.setTimeout(function() {
$('#loading').show();
loadingTimer = -1;
}, 500);
}
resourceRequests++;
return data;
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
$httpProvider.interceptors.push('spinnerInterceptor');
$httpProvider.interceptors.push('authInterceptor');
});
module.factory('spinnerInterceptor', function($q, $window, $rootScope, $location) {
return {
response: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return response;
},
responseError: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return $q.reject(response);
}
};
});
module.factory('errorInterceptor', function($q, $window, $rootScope, $location, Notifications, Auth) {
return {
response: function(response) {
return response;
},
responseError: function(response) {
if (response.status == 401) {
Auth.authz.logout();
} else if (response.status == 403) {
$location.path('/forbidden');
} else if (response.status == 404) {
$location.path('/notfound');
} else if (response.status) {
if (response.data && response.data.errorMessage) {
Notifications.error(response.data.errorMessage);
} else {
Notifications.error("An unexpected server error has occurred");
}
}
return $q.reject(response);
}
};
});
// collapsable form fieldsets
module.directive('collapsable', function() {
return function(scope, element, attrs) {
element.click(function() {
$(this).toggleClass('collapsed');
$(this).find('.toggle-icons').toggleClass('kc-icon-collapse').toggleClass('kc-icon-expand');
$(this).find('.toggle-icons').text($(this).text() == "Icon: expand" ? "Icon: collapse" : "Icon: expand");
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('uncollapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-down"></i> ');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('collapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-right"></i> ');
element.parent().find('.form-group').toggleClass('hidden');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox.
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitch [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitch', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the value to be string 'true' or 'false', not boolean true/false
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Dynamic values for id and name attributes. Useful if you need to use this directive inside a ng-repeat
* - Specific scope to specify the value. Instead of just true or false.
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" kc-onoffswitch-model [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchstring', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '=',
id: '=',
value: '=',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: '<span><div class="onoffswitch" tabindex="0"><input type="checkbox" ng-true-value="\'true\'" ng-false-value="\'false\'" ng-model="ngModel" ng-disabled="ngDisabled" class="onoffswitch-checkbox" name="kc{{name}}" id="kc{{id}}"><label for="kc{{id}}" class="onoffswitch-label"><span class="onoffswitch-inner"><span class="onoffswitch-active">{{kcOnText}}</span><span class="onoffswitch-inactive">{{kcOffText}}</span></span><span class="onoffswitch-switch"></span></label></div></span>',
compile: function(element, attrs) {
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown click', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the true-value or false-value to be string like 'true' or 'false', not boolean true/false.
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Specific scope to specify the value. Instead of just 'true' or 'false' you can use any other values. For example: true-value="'foo'" false-value="'bar'" .
* But 'true'/'false' are defaults if true-value and false-value are not specified
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitchvalue [ true-value="'true'" false-value="'false'" on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchvalue', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
trueValue: '@',
falseValue: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-true-value='{{trueValue}}' ng-false-value='{{falseValue}}' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.trueValue) { attrs.trueValue = "'true'"; }
if (!attrs.falseValue) { attrs.falseValue = "'false'"; }
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
module.directive('kcInput', function() {
var d = {
scope : true,
replace : false,
link : function(scope, element, attrs) {
var form = element.children('form');
var label = element.children('label');
var input = element.children('input');
var id = form.attr('name') + '.' + input.attr('name');
element.attr('class', 'control-group');
label.attr('class', 'control-label');
label.attr('for', id);
input.wrap('<div class="controls"/>');
input.attr('id', id);
if (!input.attr('placeHolder')) {
input.attr('placeHolder', label.text());
}
if (input.attr('required')) {
label.append(' <span class="required">*</span>');
}
}
};
return d;
});
module.directive('kcEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.kcEnter);
});
event.preventDefault();
}
});
};
});
module.directive('kcSave', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-primary");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
var ngValid = form.find('.ng-valid');
if ($scope[form.attr('name')].$valid) {
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
$scope['save']();
} else {
Notifications.error("Missing or invalid field(s). Please verify the fields in red.")
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
var ngInvalid = form.find('.ng-invalid');
//ngInvalid.addClass('error');
ngInvalid.parent().addClass('has-error');
}
}
});
})
}
}
});
module.directive('kcReset', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
form.find('.ng-valid').removeClass('error');
form.find('.ng-invalid').removeClass('error');
$scope['reset']();
}
})
})
}
}
});
module.directive('kcCancel', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
}
}
});
module.directive('kcDelete', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-danger");
elem.attr("type","submit");
}
}
});
module.directive('kcDropdown', function ($compile, Notifications) {
return {
scope: {
kcOptions: '=',
kcModel: '=',
id: "=",
kcPlaceholder: '@'
},
restrict: 'EA',
replace: true,
templateUrl: resourceUrl + '/templates/kc-select.html',
link: function(scope, element, attr) {
scope.updateModel = function(item) {
scope.kcModel = item;
};
}
}
});
module.directive('kcReadOnly', function() {
var disabled = {};
var d = {
replace : false,
link : function(scope, element, attrs) {
var disable = function(i, e) {
if (!e.disabled) {
disabled[e.tagName + i] = true;
e.disabled = true;
}
}
var enable = function(i, e) {
if (disabled[e.tagName + i]) {
e.disabled = false;
delete disabled[i];
}
}
var filterIgnored = function(i, e){
return !e.attributes['kc-read-only-ignore'];
}
scope.$watch(attrs.kcReadOnly, function(readOnly) {
if (readOnly) {
element.find('input').filter(filterIgnored).each(disable);
element.find('button').filter(filterIgnored).each(disable);
element.find('select').filter(filterIgnored).each(disable);
element.find('textarea').filter(filterIgnored).each(disable);
} else {
element.find('input').filter(filterIgnored).each(enable);
element.find('input').filter(filterIgnored).each(enable);
element.find('button').filter(filterIgnored).each(enable);
element.find('select').filter(filterIgnored).each(enable);
element.find('textarea').filter(filterIgnored).each(enable);
}
});
}
};
return d;
});
module.directive('kcMenu', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-menu.html'
}
});
module.directive('kcTabsRealm', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-realm.html'
}
});
module.directive('kcTabsAuthentication', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-authentication.html'
}
});
module.directive('kcTabsUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user.html'
}
});
module.directive('kcTabsGroup', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group.html'
}
});
module.directive('kcTabsGroupList', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group-list.html'
}
});
module.directive('kcTabsClient', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client.html'
}
});
module.directive('kcTabsClientTemplate', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client-template.html'
}
});
module.directive('kcNavigationUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-navigation-user.html'
}
});
module.directive('kcTabsIdentityProvider', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-identity-provider.html'
}
});
module.directive('kcTabsUserFederation', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user-federation.html'
}
});
module.controller('RoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ProviderConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/role-selector.html',
controller: 'RoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcProviderConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ProviderConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-provider-config.html'
}
});
module.controller('ComponentRoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName][0] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName][0] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ComponentConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/component-role-selector.html',
controller: 'ComponentRoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcComponentConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ComponentConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-component-config.html'
}
});
/*
* Used to select the element (invoke $(elem).select()) on specified action list.
* Usages kc-select-action="click mouseover"
* When used in the textarea element, this will select/highlight the textarea content on specified action (i.e. click).
*/
module.directive('kcSelectAction', function ($compile, Notifications) {
return {
restrict: 'A',
compile: function (elem, attrs) {
var events = attrs.kcSelectAction.split(" ");
for(var i=0; i < events.length; i++){
elem.bind(events[i], function(){
elem.select();
});
}
}
}
});
module.filter('remove', function() {
return function(input, remove, attribute) {
if (!input || !remove) {
return input;
}
var out = [];
for ( var i = 0; i < input.length; i++) {
var e = input[i];
if (Array.isArray(remove)) {
for (var j = 0; j < remove.length; j++) {
if (attribute) {
if (remove[j][attribute] == e[attribute]) {
e = null;
break;
}
} else {
if (remove[j] == e) {
e = null;
break;
}
}
}
} else {
if (attribute) {
if (remove[attribute] == e[attribute]) {
e = null;
}
} else {
if (remove == e) {
e = null;
}
}
}
if (e != null) {
out.push(e);
}
}
return out;
};
});
module.filter('capitalize', function() {
return function(input) {
if (!input) {
return;
}
var splittedWords = input.split(/\s+/);
for (var i=0; i<splittedWords.length ; i++) {
splittedWords[i] = splittedWords[i].charAt(0).toUpperCase() + splittedWords[i].slice(1);
};
return splittedWords.join(" ");
};
});
/*
* Guarantees a deterministic property iteration order.
* See: http://www.2ality.com/2015/10/property-traversal-order-es6.html
*/
module.filter('toOrderedMapSortedByKey', function(){
return function(input){
if(!input){
return input;
}
var keys = Object.keys(input);
if(keys.length <= 1){
return input;
}
keys.sort();
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = input[keys[i]];
}
return result;
};
});
module.directive('kcSidebarResize', function ($window) {
return function (scope, element) {
function resize() {
var navBar = angular.element(document.getElementsByClassName('navbar-pf')).height();
var container = angular.element(document.getElementById("view").getElementsByTagName("div")[0]).height();
var height = Math.max(container, window.innerHeight - navBar - 3);
element[0].style['min-height'] = height + 'px';
}
resize();
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function () {
resize();
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
module.directive('kcTooltip', function($compile) {
return {
restrict: 'E',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
var angularElement = angular.element(element[0]);
var tooltip = angularElement.text();
angularElement.text('');
element.addClass('hidden');
var label = angular.element(element.parent().children()[0]);
label.append(' <i class="fa fa-question-circle text-muted" tooltip="' + tooltip + '" tooltip-placement="right" tooltip-trigger="mouseover mouseout"></i>');
$compile(label)(scope);
}
};
});
module.directive( 'kcOpen', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'kcOpen', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path(path);
});
});
};
});
module.directive('kcOnReadFile', function ($parse) {
console.debug('kcOnReadFile');
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.kcOnReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
| wildfly-security-incubator/keycloak | themes/src/main/resources/theme/base/admin/resources/js/app.js | JavaScript | apache-2.0 | 99,144 |
/*
* AnyOf_test.cpp
*
* Created on: Jan 30, 2016
* Author: ljeff
*/
#include "AnyOf.h"
namespace algorithm {
} /* namespace algorithm */
| jidol/boost-algorithms | AnyOf_test.cpp | C++ | apache-2.0 | 151 |
/*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.persistence;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.Assert;
import org.mifos.accounts.business.AccountActionDateEntity;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.business.AccountTestUtils;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.FeeBO;
import org.mifos.accounts.fees.util.helpers.FeeCategory;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.RecommendedAmountUnit;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStateFlag;
import org.mifos.accounts.util.helpers.AccountTypes;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.exceptions.MeetingException;
import org.mifos.application.meeting.persistence.MeetingPersistence;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.servicefacade.CollectionSheetCustomerDto;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.config.AccountingRulesConstants;
import org.mifos.config.ConfigurationManager;
import org.mifos.core.CurrencyMismatchException;
import org.mifos.customers.business.CustomerAccountBO;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerBOTestUtils;
import org.mifos.customers.business.CustomerNoteEntity;
import org.mifos.customers.business.CustomerPerformanceHistoryView;
import org.mifos.customers.business.CustomerSearch;
import org.mifos.customers.business.CustomerStatusEntity;
import org.mifos.customers.business.CustomerView;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.checklist.business.CheckListBO;
import org.mifos.customers.checklist.business.CustomerCheckListBO;
import org.mifos.customers.checklist.util.helpers.CheckListConstants;
import org.mifos.customers.client.business.AttendanceType;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.client.util.helpers.ClientConstants;
import org.mifos.customers.group.BasicGroupInfo;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.ChildrenStateType;
import org.mifos.customers.util.helpers.CustomerLevel;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.customers.util.helpers.CustomerStatusFlag;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;
public class CustomerPersistenceIntegrationTest extends MifosIntegrationTestCase {
public CustomerPersistenceIntegrationTest() throws Exception {
super();
}
private MeetingBO meeting;
private CustomerBO center;
private ClientBO client;
private CustomerBO group2;
private CustomerBO group;
private AccountBO account;
private LoanBO groupAccount;
private LoanBO clientAccount;
private SavingsBO centerSavingsAccount;
private SavingsBO groupSavingsAccount;
private SavingsBO clientSavingsAccount;
private SavingsOfferingBO savingsOffering;
private final CustomerPersistence customerPersistence = new CustomerPersistence();
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
try {
TestObjectFactory.cleanUp(centerSavingsAccount);
TestObjectFactory.cleanUp(groupSavingsAccount);
TestObjectFactory.cleanUp(clientSavingsAccount);
TestObjectFactory.cleanUp(groupAccount);
TestObjectFactory.cleanUp(clientAccount);
TestObjectFactory.cleanUp(account);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group2);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
StaticHibernateUtil.closeSession();
} catch (Exception e) {
// Throwing from tearDown will tend to mask the real failure.
e.printStackTrace();
}
super.tearDown();
}
public void testGetTotalAmountForAllClientsOfGroupForSingleCurrency() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.RUPEE);
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(TestUtils.RUPEE, "600"), amount);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForAllClientsOfGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
AccountBO clientAccount1;
AccountBO clientAccount2;
try {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
GroupBO group1;
AccountBO account1;
AccountBO account2;
try {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf", TestUtils.RUPEE);
account2 = getLoanAccount(group1, meeting, "adspp", "kkaf", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForGroup() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
AccountBO account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf");
AccountBO account2 = getLoanAccount(group1, meeting, "adspp", "kkaf");
Money amount = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
AccountBO account3 = getLoanAccountInActiveBadStanding(group1, meeting, "adsfdsfsd1", "4sa");
AccountBO account4 = getLoanAccountInActiveBadStanding(group1, meeting, "adspp2", "kaf5");
Money amount2 = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForAllClientsOfGroup() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe");
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
clientAccount1.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
clientAccount2.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
TestObjectFactory.updateObject(clientAccount1);
TestObjectFactory.updateObject(clientAccount2);
StaticHibernateUtil.commitTransaction();
Money amount2 = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
public void testGetAllBasicGroupInfo() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
GroupBO newGroup = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup", CustomerStatus.GROUP_HOLD, center);
GroupBO newGroup2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup2", CustomerStatus.GROUP_CANCELLED,
center);
GroupBO newGroup3 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup3", CustomerStatus.GROUP_CLOSED, center);
GroupBO newGroup4 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup4", CustomerStatus.GROUP_PARTIAL, center);
GroupBO newGroup5 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup5", CustomerStatus.GROUP_PENDING, center);
List<BasicGroupInfo> groupInfos = customerPersistence.getAllBasicGroupInfo();
Assert.assertEquals(2, groupInfos.size());
Assert.assertEquals(group.getDisplayName(), groupInfos.get(0).getGroupName());
Assert.assertEquals(group.getSearchId(), groupInfos.get(0).getSearchId());
Assert.assertEquals(group.getOffice().getOfficeId(), groupInfos.get(0).getBranchId());
Assert.assertEquals(group.getCustomerId(), groupInfos.get(0).getGroupId());
Assert.assertEquals(newGroup.getDisplayName(), groupInfos.get(1).getGroupName());
Assert.assertEquals(newGroup.getSearchId(), groupInfos.get(1).getSearchId());
Assert.assertEquals(newGroup.getOffice().getOfficeId(), groupInfos.get(1).getBranchId());
Assert.assertEquals(newGroup.getCustomerId(), groupInfos.get(1).getGroupId());
TestObjectFactory.cleanUp(newGroup);
TestObjectFactory.cleanUp(newGroup2);
TestObjectFactory.cleanUp(newGroup3);
TestObjectFactory.cleanUp(newGroup4);
TestObjectFactory.cleanUp(newGroup5);
}
public void testCustomersUnderLO() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center_Active", meeting);
List<CustomerView> customers = customerPersistence.getActiveParentList(Short.valueOf("1"), CustomerLevel.CENTER
.getValue(), Short.valueOf("3"));
Assert.assertEquals(1, customers.size());
}
public void testActiveCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testOnHoldCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_HOLD, CustomerStatus.CLIENT_HOLD);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testGetLastMeetingDateForCustomer() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
account = getLoanAccount(group, meeting, "adsfdsfsd", "3saf");
// Date actionDate = new Date(2006,03,13);
Date meetingDate = customerPersistence.getLastMeetingDateForCustomer(center.getCustomerId());
Assert.assertEquals(new Date(getMeetingDates(meeting).getTime()).toString(), meetingDate.toString());
}
public void testGetChildernOtherThanClosed() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CLOSED);
Assert.assertEquals(new Integer("3").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client3.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernActiveAndHold() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_PARTIAL, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_PENDING, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_HOLD, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ACTIVE_AND_ONHOLD);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
if (customer.getCustomerId().intValue() == client4.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernOtherThanClosedAndCancelled() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CANCELLED_AND_CLOSED);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client4.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetAllChildern() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ALL);
Assert.assertEquals(new Integer("4").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client2.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testRetrieveSavingsAccountForCustomer() throws Exception {
java.util.Date currentDate = new java.util.Date();
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "S", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
UserContext user = new UserContext();
user.setId(PersonnelConstants.SYSTEM_USER);
account = TestObjectFactory.createSavingsAccount("000100000000020", group, AccountState.SAVINGS_ACTIVE,
currentDate, savingsOffering, user);
StaticHibernateUtil.closeSession();
List<SavingsBO> savingsList = customerPersistence.retrieveSavingsAccountForCustomer(group.getCustomerId());
Assert.assertEquals(1, savingsList.size());
account = savingsList.get(0);
group = account.getCustomer();
center = group.getParentCustomer();
}
public void testNumberOfMeetingsAttended() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.LATE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(true,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsAttended().intValue());
StaticHibernateUtil.closeSession();
}
public void testNumberOfMeetingsMissed() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.APPROVED_LEAVE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(false,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsMissed().intValue());
StaticHibernateUtil.closeSession();
}
public void testLastLoanAmount() throws PersistenceException, AccountException {
Date startDate = new Date(System.currentTimeMillis());
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, center.getCustomerMeeting()
.getMeeting());
LoanBO loanBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
account = (AccountBO) StaticHibernateUtil.getSessionTL().get(LoanBO.class, loanBO.getAccountId());
AccountStateEntity accountStateEntity = new AccountStateEntity(AccountState.LOAN_CLOSED_OBLIGATIONS_MET);
account.setUserContext(TestObjectFactory.getContext());
account.changeStatus(accountStateEntity.getId(), null, "");
TestObjectFactory.updateObject(account);
CustomerPersistence customerPersistence = new CustomerPersistence();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.getLastLoanAmount(client
.getCustomerId());
Assert.assertEquals("300.0", customerPerformanceHistoryView.getLastLoanAmount());
}
public void testFindBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testGetBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum(), group
.getCustomerLevel().getId());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testOptionalCustomerStates() throws Exception {
Assert.assertEquals(Integer.valueOf(0).intValue(), customerPersistence.getCustomerStates(Short.valueOf("0"))
.size());
}
public void testCustomerStatesInUse() throws Exception {
Assert.assertEquals(Integer.valueOf(14).intValue(), customerPersistence.getCustomerStates(Short.valueOf("1"))
.size());
}
public void testGetCustomersWithUpdatedMeetings() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
CustomerBOTestUtils.setUpdatedFlag(group.getCustomerMeeting(), YesNoFlag.YES.getValue());
TestObjectFactory.updateObject(group);
List<Integer> customerIds = customerPersistence.getCustomersWithUpdatedMeetings();
Assert.assertEquals(1, customerIds.size());
}
public void testRetrieveAllLoanAccountUnderCustomer() throws PersistenceException {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_ACTIVE, group1);
account = getLoanAccount(group, meeting, "cdfggdfs", "1qdd");
AccountBO account1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO account2 = getLoanAccount(client2, meeting, "fasdfdsfasdf", "1qwe");
AccountBO account3 = getLoanAccount(client3, meeting, "fdsgdfgfd", "543g");
AccountBO account4 = getLoanAccount(group1, meeting, "fasdf23", "3fds");
CustomerBOTestUtils.setCustomerStatus(client2, new CustomerStatusEntity(CustomerStatus.CLIENT_CLOSED));
TestObjectFactory.updateObject(client2);
client2 = TestObjectFactory.getClient(client2.getCustomerId());
CustomerBOTestUtils.setCustomerStatus(client3, new CustomerStatusEntity(CustomerStatus.CLIENT_CANCELLED));
TestObjectFactory.updateObject(client3);
client3 = TestObjectFactory.getClient(client3.getCustomerId());
List<AccountBO> loansForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForCenter.size());
List<AccountBO> loansForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForGroup.size());
List<AccountBO> loansForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(1, loansForClient.size());
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testRetrieveAllSavingsAccountUnderCustomer() throws Exception {
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("new_center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
account = getSavingsAccount(center, "Savings Prd1", "Abc1");
AccountBO account1 = getSavingsAccount(client, "Savings Prd2", "Abc2");
AccountBO account2 = getSavingsAccount(client2, "Savings Prd3", "Abc3");
AccountBO account3 = getSavingsAccount(client3, "Savings Prd4", "Abc4");
AccountBO account4 = getSavingsAccount(group1, "Savings Prd5", "Abc5");
AccountBO account5 = getSavingsAccount(group, "Savings Prd6", "Abc6");
AccountBO account6 = getSavingsAccount(center1, "Savings Prd7", "Abc7");
List<AccountBO> savingsForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(4, savingsForCenter.size());
List<AccountBO> savingsForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(3, savingsForGroup.size());
List<AccountBO> savingsForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(1, savingsForClient.size());
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account5);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(account6);
TestObjectFactory.cleanUp(center1);
}
public void testGetAllChildrenForParent() throws NumberFormatException, PersistenceException {
center = createCenter("Center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<CustomerBO> customerList1 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerList1.size());
List<CustomerBO> customerList2 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.GROUP.getValue());
Assert.assertEquals(1, customerList2.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetChildrenForParent() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getChildrenForParent(center.getSearchId(), Short.valueOf("3"));
Assert.assertEquals(3, customerIds.size());
CustomerBO customer = TestObjectFactory.getCustomer(customerIds.get(0));
Assert.assertEquals("Group", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(1));
Assert.assertEquals("client1", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(2));
Assert.assertEquals("client2", customer.getDisplayName());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomers() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getCustomers(CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerIds.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomerChecklist() throws NumberFormatException, SystemException, ApplicationException,
Exception {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
CustomerCheckListBO checklistCenter = TestObjectFactory.createCustomerChecklist(center.getCustomerLevel()
.getId(), center.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
CustomerCheckListBO checklistClient = TestObjectFactory.createCustomerChecklist(client.getCustomerLevel()
.getId(), client.getCustomerStatus().getId(), CheckListConstants.STATUS_INACTIVE);
CustomerCheckListBO checklistGroup = TestObjectFactory.createCustomerChecklist(
group.getCustomerLevel().getId(), group.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
StaticHibernateUtil.closeSession();
Assert.assertEquals(1, customerPersistence.getStatusChecklist(center.getCustomerStatus().getId(),
center.getCustomerLevel().getId()).size());
client = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class,
Integer.valueOf(client.getCustomerId()));
group = (GroupBO) StaticHibernateUtil.getSessionTL().get(GroupBO.class, Integer.valueOf(group.getCustomerId()));
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
checklistCenter = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistCenter.getChecklistId()));
checklistClient = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistClient.getChecklistId()));
checklistGroup = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistGroup.getChecklistId()));
TestObjectFactory.cleanUp(checklistCenter);
TestObjectFactory.cleanUp(checklistClient);
TestObjectFactory.cleanUp(checklistGroup);
}
public void testRetrieveAllCustomerStatusList() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(2, customerPersistence.retrieveAllCustomerStatusList(center.getCustomerLevel().getId())
.size());
}
public void testCustomerCountByOffice() throws Exception {
int count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(0, count);
center = createCenter();
count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(1, count);
}
public void testGetAllCustomerNotes() throws Exception {
center = createCenter();
center.addCustomerNotes(TestObjectFactory.getCustomerNote("Test Note", center));
TestObjectFactory.updateObject(center);
Assert.assertEquals(1, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
for (CustomerNoteEntity note : center.getCustomerNotes()) {
Assert.assertEquals("Test Note", note.getComment());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), note.getPersonnel().getPersonnelId());
}
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
}
public void testGetAllCustomerNotesWithZeroNotes() throws Exception {
center = createCenter();
Assert.assertEquals(0, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
Assert.assertEquals(0, center.getCustomerNotes().size());
}
public void testGetFormedByPersonnel() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(1, customerPersistence.getFormedByPersonnel(ClientConstants.LOAN_OFFICER_LEVEL,
center.getOffice().getOfficeId()).size());
}
public void testGetAllClosedAccounts() throws Exception {
getCustomer();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
clientAccount.changeStatus(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue(), null, "WITHDRAW LOAN ACCOUNT");
clientSavingsAccount.changeStatus(AccountState.SAVINGS_CANCELLED.getValue(), AccountStateFlag.SAVINGS_REJECTED
.getValue(), "WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
TestObjectFactory.updateObject(clientAccount);
TestObjectFactory.updateObject(clientSavingsAccount);
StaticHibernateUtil.commitTransaction();
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetAllClosedAccountsWhenNoAccountsClosed() throws Exception {
getCustomer();
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetLOForCustomer() throws PersistenceException {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Short LO = customerPersistence.getLoanOfficerForCustomer(center.getCustomerId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), LO);
}
public void testUpdateLOsForAllChildren() {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildren(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = TestObjectFactory.getCenter(center.getCustomerId());
group = TestObjectFactory.getGroup(group.getCustomerId());
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertEquals(newLO.getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(newLO.getPersonnelId(), client.getPersonnel().getPersonnelId());
}
public void testUpdateLOsForAllChildrenAccounts() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildrenAccounts(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
for (AccountBO account : client.getAccounts()) {
Assert.assertEquals(newLO.getPersonnelId(), account.getPersonnel().getPersonnelId());
}
}
public void testCustomerDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
client = TestObjectFactory.createClient("myClient", meeting, CustomerStatus.CLIENT_PENDING);
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
customerPersistence.deleteCustomerMeeting(client);
CustomerBOTestUtils.setCustomerMeeting(client, null);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertNull(client.getCustomerMeeting());
}
public void testDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
customerPersistence.deleteMeeting(meeting);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
Assert.assertNull(meeting);
}
public void testSearchWithOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("3"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithoutOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("0"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithGlobalNo() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchWithGovernmentId() throws Exception {
createCustomersWithGovernmentId(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("76346793216", Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
@SuppressWarnings("unchecked")
public void testSearchWithCancelLoanAccounts() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(0, customerSearch.getLoanGlobalAccountNum().size());
}
public void testSearchWithAccountGlobalNo() throws Exception {
getCustomer();
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(groupAccount.getGlobalAccountNum(), Short
.valueOf("3"), Short.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClient() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLoNoResults() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(0, queryResult.getSize());
Assert.assertEquals(0, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLo() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("G", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchCustForSavings() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchCustForSavings("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testGetCustomerAccountsForFee() throws Exception {
groupAccount = getLoanAccount();
FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("ClientPeridoicFee", FeeCategory.CENTER, "5",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountFee = new AccountFeesEntity(center.getCustomerAccount(), periodicFee,
((AmountFeeBO) periodicFee).getFeeAmount().getAmountDoubleValue());
CustomerAccountBO customerAccount = center.getCustomerAccount();
AccountTestUtils.addAccountFees(accountFee, customerAccount);
TestObjectFactory.updateObject(customerAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
// check for the account fee
List<AccountBO> accountList = new CustomerPersistence().getCustomerAccountsForFee(periodicFee.getFeeId());
Assert.assertNotNull(accountList);
Assert.assertEquals(1, accountList.size());
Assert.assertTrue(accountList.get(0) instanceof CustomerAccountBO);
// get all objects again
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
}
public void testRetrieveCustomerAccountActionDetails() throws Exception {
center = createCenter();
Assert.assertNotNull(center.getCustomerAccount());
List<AccountActionDateEntity> actionDates = new CustomerPersistence().retrieveCustomerAccountActionDetails(
center.getCustomerAccount().getAccountId(), new java.sql.Date(System.currentTimeMillis()));
Assert.assertEquals("The size of the due insallments is ", actionDates.size(), 1);
}
public void testGetActiveCentersUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getActiveCentersUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
public void testgetGroupsUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
group2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group33", CustomerStatus.GROUP_CANCELLED, center);
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getGroupsUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
@SuppressWarnings("unchecked")
public void testSearchForActiveInBadStandingLoanAccount() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "Changing to badStanding");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(1, customerSearch.getLoanGlobalAccountNum().size());
}
public void testGetCustomersByLevelId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
List<CustomerBO> client = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("1"));
Assert.assertNotNull(client);
Assert.assertEquals(1, client.size());
List<CustomerBO> group = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("2"));
Assert.assertNotNull(group);
Assert.assertEquals(1, group.size());
List<CustomerBO> center = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("3"));
Assert.assertNotNull(center);
Assert.assertEquals(1, center.size());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
verifyCustomerLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnInactiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Inactive Center", meeting);
center.changeStatus(CustomerStatus.CENTER_INACTIVE, CustomerStatusFlag.GROUP_CANCEL_BLACKLISTED, "Made Inactive");
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class, center.getCustomerId());
verifyCustomerNotLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Hold Group", CustomerStatus.GROUP_HOLD,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Closed Group", CustomerStatus.GROUP_CLOSED,
center);
verifyCustomerNotLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Active Client", CustomerStatus.CLIENT_ACTIVE, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Hold Client", CustomerStatus.CLIENT_HOLD, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Closed Client", CustomerStatus.CLIENT_CLOSED, group);
verifyCustomerNotLoaded(client.getCustomerId(), client.getDisplayName());
}
private void verifyCustomerLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNotNull(customerName + " was not returned", collectionSheetCustomerDto);
Assert.assertEquals(collectionSheetCustomerDto.getCustomerId(), customerId);
}
private void verifyCustomerNotLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNull(customerName + " was returned", collectionSheetCustomerDto);
}
private AccountBO getSavingsAccount(final CustomerBO customer, final String prdOfferingname, final String shortName)
throws Exception {
Date startDate = new Date(System.currentTimeMillis());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct(prdOfferingname, shortName,
startDate, RecommendedAmountUnit.COMPLETE_GROUP);
return TestObjectFactory.createSavingsAccount("432434", customer, Short.valueOf("16"), startDate,
savingsOffering);
}
private void getCustomer() throws Exception {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering("Loanwer", "43fs", startDate, meeting);
LoanOfferingBO loanOffering2 = TestObjectFactory.createLoanOffering("Loancd123", "vfr", startDate, meeting);
groupAccount = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering1);
clientAccount = TestObjectFactory.createLoanAccount("3243", client, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering2);
MeetingBO meetingIntCalc = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
MeetingBO meetingIntPost = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd12", "abc1", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
SavingsOfferingBO savingsOffering1 = TestObjectFactory.createSavingsProduct("SavingPrd11", "abc2", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
centerSavingsAccount = TestObjectFactory.createSavingsAccount("432434", center, Short.valueOf("16"), startDate,
savingsOffering);
clientSavingsAccount = TestObjectFactory.createSavingsAccount("432434", client, Short.valueOf("16"), startDate,
savingsOffering1);
}
private void createCustomers(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group);
}
private void createCustomersWithGovernmentId(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group, TestObjectFactory.getFees(), "76346793216", new java.util.Date(1222333444000L));
}
private static java.util.Date getMeetingDates(final MeetingBO meeting) {
List<java.util.Date> dates = new ArrayList<java.util.Date>();
try {
dates = meeting.getAllDates(new java.util.Date(System.currentTimeMillis()));
} catch (MeetingException e) {
e.printStackTrace();
}
return dates.get(dates.size() - 1);
}
private CenterBO createCenter() {
return createCenter("Center_Active_test");
}
private CenterBO createCenter(final String name) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
return TestObjectFactory.createWeeklyFeeCenter(name, meeting);
}
private LoanBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName, MifosCurrency currency) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting, currency);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccountInActiveBadStanding(final CustomerBO group, final MeetingBO meeting,
final String offeringName, final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423141111", group, AccountState.LOAN_ACTIVE_IN_BAD_STANDING,
startDate, loanOffering);
}
}
| mifos/1.5.x | application/src/test/java/org/mifos/customers/persistence/CustomerPersistenceIntegrationTest.java | Java | apache-2.0 | 73,142 |
/**
*
* @author Alex Karpov (mailto:karpov_aleksey@mail.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.max; | AlekseyKarpov/akarpov | chapter_001/src/test/java/ru/job4j/max/package-info.java | Java | apache-2.0 | 113 |
package com.capgemini.resilience.employer.service;
public interface ErrorSimulationService {
void generateErrorDependingOnErrorPossibility();
}
| microservices-summit-2016/resilience-demo | employer-service/src/main/java/com/capgemini/resilience/employer/service/ErrorSimulationService.java | Java | apache-2.0 | 150 |
using UnityEngine;
using System.Collections;
public class blockGenerator : MonoBehaviour {
public int spawnRate = 1;
private float timeSinceLastSpawn = 0;
public GameObject oneCube;
public int count;
// Use this for initialization
void Start () {
//Debug.Log("ran cube creator");
count = 0;
}
// Update is called once per frame
void Update () {
//timeSinceLastSpawn += Time.realtimeSinceStartup;
//Debug.Log("running cube creator" + timeSinceLastSpawn );
// if ( timeSinceLastSpawn > spawnRate )
// {
//Clone the cubes and randomly place them
count = count + 1;
if (count.Equals(50)) {
GameObject newCube = (GameObject)GameObject.Instantiate (oneCube);
newCube.transform.position = new Vector3 (0, 0, 20.0f);
newCube.transform.Translate (Random.Range (-8, 8), Random.Range (0, 8), 1.0f);
timeSinceLastSpawn = 0;
//Debug.Log("cube created");
// }
count = 0;
}
}
} | josejlm2/HackTx2014 | Assets/Resources/Scripts/blockGenerator.cs | C# | apache-2.0 | 938 |
// -----------------------------------------------------------------------
// <copyright file="Health.cs" company="PlayFab Inc">
// Copyright 2015 PlayFab Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------
using System.Threading;
using System.Threading.Tasks;
namespace Consul
{
public interface IHealthEndpoint
{
Task<QueryResult<HealthCheck[]>> Checks(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Checks(string service, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, QueryOptions q, CancellationToken ct = default(CancellationToken));
}
} | PlayFab/consuldotnet | Consul/Interfaces/IHealthEndpoint.cs | C# | apache-2.0 | 2,271 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RestHandler.h"
#include "Basics/StringUtils.h"
#include "Dispatcher/Dispatcher.h"
#include "Logger/Logger.h"
#include "Rest/GeneralRequest.h"
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
namespace {
std::atomic_uint_fast64_t NEXT_HANDLER_ID(
static_cast<uint64_t>(TRI_microtime() * 100000.0));
}
RestHandler::RestHandler(GeneralRequest* request, GeneralResponse* response)
: _handlerId(NEXT_HANDLER_ID.fetch_add(1, std::memory_order_seq_cst)),
_taskId(0),
_request(request),
_response(response) {}
RestHandler::~RestHandler() {
delete _request;
delete _response;
}
void RestHandler::setTaskId(uint64_t id, EventLoop loop) {
_taskId = id;
_loop = loop;
}
RestHandler::status RestHandler::executeFull() {
RestHandler::status result = status::FAILED;
requestStatisticsAgentSetRequestStart();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = _statistics;
#endif
try {
prepareExecute();
try {
result = execute();
} catch (Exception const& ex) {
requestStatisticsAgentSetExecuteError();
handleError(ex);
} catch (std::bad_alloc const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_OUT_OF_MEMORY, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (std::exception const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (...) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, __FILE__, __LINE__);
handleError(err);
}
finalizeExecute();
if (result != status::ASYNC && _response == nullptr) {
Exception err(TRI_ERROR_INTERNAL, "no response received from handler",
__FILE__, __LINE__);
handleError(err);
}
} catch (Exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << DIAGNOSTIC_INFORMATION(ex);
} catch (std::exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << ex.what();
} catch (...) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception";
}
requestStatisticsAgentSetRequestEnd();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = nullptr;
#endif
return result;
}
GeneralRequest* RestHandler::stealRequest() {
GeneralRequest* tmp = _request;
_request = nullptr;
return tmp;
}
GeneralResponse* RestHandler::stealResponse() {
GeneralResponse* tmp = _response;
_response = nullptr;
return tmp;
}
void RestHandler::setResponseCode(GeneralResponse::ResponseCode code) {
TRI_ASSERT(_response != nullptr);
_response->reset(code);
}
| m0ppers/arangodb | arangod/GeneralServer/RestHandler.cpp | C++ | apache-2.0 | 3,855 |
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git.receive;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.Change;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* Keeps track of the change IDs thus far updated by ReceiveCommit.
*
* <p>This class is thread-safe.
*/
public class ResultChangeIds {
public enum Key {
CREATED,
REPLACED,
AUTOCLOSED,
}
private boolean isMagicPush;
private final Map<Key, List<Change.Id>> ids;
ResultChangeIds() {
ids = new EnumMap<>(Key.class);
for (Key k : Key.values()) {
ids.put(k, new ArrayList<>());
}
}
/** Record a change ID update as having completed. Thread-safe. */
public synchronized void add(Key key, Change.Id id) {
ids.get(key).add(id);
}
/** Indicate that the ReceiveCommits call involved a magic branch. */
public synchronized void setMagicPush(boolean magic) {
isMagicPush = magic;
}
public synchronized boolean isMagicPush() {
return isMagicPush;
}
/**
* Returns change IDs of the given type for which the BatchUpdate succeeded, or empty list if
* there are none. Thread-safe.
*/
public synchronized List<Change.Id> get(Key key) {
return ImmutableList.copyOf(ids.get(key));
}
}
| qtproject/qtqa-gerrit | java/com/google/gerrit/server/git/receive/ResultChangeIds.java | Java | apache-2.0 | 1,920 |
# Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import shutil
import argparse
from .. import mlog
from ..mesonlib import has_path_sep
from . import destdir_join
from .gettext import read_linguas
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('--id', dest='project_id')
parser.add_argument('--subdir', dest='subdir')
parser.add_argument('--installdir', dest='install_dir')
parser.add_argument('--sources', dest='sources')
parser.add_argument('--media', dest='media', default='')
parser.add_argument('--langs', dest='langs', default='')
parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False)
def build_pot(srcdir, project_id, sources):
# Must be relative paths
sources = [os.path.join('C', source) for source in sources]
outfile = os.path.join(srcdir, project_id + '.pot')
subprocess.call(['itstool', '-o', outfile] + sources)
def update_po(srcdir, project_id, langs):
potfile = os.path.join(srcdir, project_id + '.pot')
for lang in langs:
pofile = os.path.join(srcdir, lang, lang + '.po')
subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
def build_translations(srcdir, blddir, langs):
for lang in langs:
outdir = os.path.join(blddir, lang)
os.makedirs(outdir, exist_ok=True)
subprocess.call([
'msgfmt', os.path.join(srcdir, lang, lang + '.po'),
'-o', os.path.join(outdir, lang + '.gmo')
])
def merge_translations(blddir, sources, langs):
for lang in langs:
subprocess.call([
'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'),
'-o', os.path.join(blddir, lang)
] + sources)
def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks):
c_install_dir = os.path.join(install_dir, 'C', project_id)
for lang in langs + ['C']:
indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id))
os.makedirs(indir, exist_ok=True)
for source in sources:
infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source)
outfile = os.path.join(indir, source)
mlog.log('Installing %s to %s' % (infile, outfile))
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
for m in media:
infile = os.path.join(srcdir, lang, m)
outfile = os.path.join(indir, m)
c_infile = os.path.join(srcdir, 'C', m)
if not os.path.exists(infile):
if not os.path.exists(c_infile):
mlog.warning('Media file "%s" did not exist in C directory' % m)
continue
elif symlinks:
srcfile = os.path.join(c_install_dir, m)
mlog.log('Symlinking %s to %s.' % (outfile, srcfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
try:
try:
os.symlink(srcfile, outfile)
except FileExistsError:
os.remove(outfile)
os.symlink(srcfile, outfile)
continue
except (NotImplementedError, OSError):
mlog.warning('Symlinking not supported, falling back to copying')
infile = c_infile
else:
# Lang doesn't have media file so copy it over 'C' one
infile = c_infile
mlog.log('Installing %s to %s' % (infile, outfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
def run(args):
options = parser.parse_args(args)
langs = options.langs.split('@@') if options.langs else []
media = options.media.split('@@') if options.media else []
sources = options.sources.split('@@')
destdir = os.environ.get('DESTDIR', '')
src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir)
build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir)
abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources]
if not langs:
langs = read_linguas(src_subdir)
if options.command == 'pot':
build_pot(src_subdir, options.project_id, sources)
elif options.command == 'update-po':
build_pot(src_subdir, options.project_id, sources)
update_po(src_subdir, options.project_id, langs)
elif options.command == 'build':
if langs:
build_translations(src_subdir, build_subdir, langs)
elif options.command == 'install':
install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir)
if langs:
build_translations(src_subdir, build_subdir, langs)
merge_translations(build_subdir, abs_sources, langs)
install_help(src_subdir, build_subdir, sources, media, langs, install_dir,
destdir, options.project_id, options.symlinks)
| becm/meson | mesonbuild/scripts/yelphelper.py | Python | apache-2.0 | 5,816 |
package com.veneweather.android;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.veneweather.android.db.City;
import com.veneweather.android.db.County;
import com.veneweather.android.db.Province;
import com.veneweather.android.util.HttpUtil;
import com.veneweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by lenovo on 2017/4/10.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button btn_back;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
btn_back = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else if (currentLevel == LEVEL_COUNTY) {
queryCities();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces() {
titleText.setText("中国");
btn_back.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中省内所有市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
btn_back.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
btn_back.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCitycode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
| Ackerm-Zed/veneweather | app/src/main/java/com/veneweather/android/ChooseAreaFragment.java | Java | apache-2.0 | 9,584 |
#
#Programa Lista 4, questão 1;
#Felipe Henrique Bastos Costa - 1615310032;
#
#
#
#
lista = []#lista vazia;
cont1 = 0#contador do indice;
cont2 = 1#contador da posição do numero, se é o primeiro, segundo etc;
v = 5#representaria o len da lista;
while(cont1 < v):
x = int(input("Informe o %dº numero inteiro para colocar em sua lista:\n"%cont2))#x e a variavel que recebe
#o numero do usuario
lista.append(x)#o numero informado para x e colocado dentro da lista;
cont1+=1#Os contadores estao
cont2+=1#sendo incrementados;
print("A lista de informada foi:\n%s"%lista)
| any1m1c/ipc20161 | lista4/ipc_lista4.01.py | Python | apache-2.0 | 675 |
#include "stdafx.h"
#include "InputReader.h"
#include "graph.h"
#include <iostream>
#include <string>
using namespace std;
InputReader::InputReader(const char* fileName, const char* stFileName)
{
in.open(fileName);
if(!in.is_open())
{
cout<<"Input file "<<fileName<<" doesn't exist!"<<endl;
exit(1);
}
stIn.open(stFileName);
if(!stIn.is_open())
{
cout<<"Input file "<<stFileName<<" doesn't exist!"<<endl;
in.close();
exit(1);
}
}
InputReader::~InputReader()
{
in.close();
stIn.close();
}
void InputReader::ReadFirstLine()
{
in>>strLine;
assert(strLine[0] == 'g');
in>>strLine;
assert(strLine[0] == '#');
in>> gId;
}
bool InputReader::ReadGraph(Graph &g)
{
ReadFirstLine();
if(gId == 0)
{
return false; /*ÒѾûÓÐͼ*/
}
g.nId = gId;
in>>strLine;
assert(strLine[0] == 's'); /*¶ÁÈ¡¶¥µãÊýºÍ±ßÊý*/
in>>g.nV>>g.nE;
assert(g.nV < MAX); /*·ÀÖ¹ÁÚ½Ó¾ØÕó´óС²»¹»ÓÃ*/
/*ÏÂÃæ¶ÁÈ¡±ßµÄÐÅÏ¢*/
int u,v; /*u,vÊÇÒ»Ìõ±ßµÄÁ½¸ö¶¥µã*/
for(int i = 1; i <= g.nE; i++)
{
in>>strLine;
assert(strLine[0] == 'e');
in>>u>>v; /*×¢ÒâÕâ¸ö²»ÄÜÓëÏÂÃæµÄдµ½Ò»Æð*/
in>>g.matrix[u][v].iC>>g.matrix[u][v].dP>>g.matrix[u][v].iLabel;
}
return true;
}
void InputReader::ReadSourceSink(int &s, int &t)
{
stIn>>s>>t;
} | yuanmouren1hao/KeyEdge_Mining_On_UncertainGraph | myFlow_caiwei/myFlow/InputReader.cpp | C++ | apache-2.0 | 1,474 |
<?php
namespace Illuminate\Database\Eloquent;
use Closure;
use BadMethodCallException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Pagination\Paginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Concerns\BuildsQueries;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
/**
* @mixin \Illuminate\Database\Query\Builder
*/
class Builder
{
use BuildsQueries, Concerns\QueriesRelationships;
/**
* The base query builder instance.
*
* @var \Illuminate\Database\Query\Builder
*/
protected $query;
/**
* The model being queried.
*
* @var \Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* The relationships that should be eager loaded.
*
* @var array
*/
protected $eagerLoad = [];
/**
* All of the globally registered builder macros.
*
* @var array
*/
protected static $macros = [];
/**
* All of the locally registered builder macros.
*
* @var array
*/
protected $localMacros = [];
/**
* A replacement for the typical delete function.
*
* @var \Closure
*/
protected $onDelete;
/**
* The methods that should be returned from query builder.
*
* @var array
*/
protected $passthru = [
'insert', 'insertGetId', 'getBindings', 'toSql',
'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'sum', 'getConnection',
];
/**
* Applied global scopes.
*
* @var array
*/
protected $scopes = [];
/**
* Removed global scopes.
*
* @var array
*/
protected $removedScopes = [];
/**
* Create a new Eloquent query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return void
*/
public function __construct(QueryBuilder $query)
{
$this->query = $query;
}
/**
* Create and return an un-saved model instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function make(array $attributes = [])
{
return $this->newModelInstance($attributes);
}
/**
* Register a new global scope.
*
* @param string $identifier
* @param \Illuminate\Database\Eloquent\Scope|\Closure $scope
* @return $this
*/
public function withGlobalScope($identifier, $scope)
{
$this->scopes[$identifier] = $scope;
if (method_exists($scope, 'extend')) {
$scope->extend($this);
}
return $this;
}
/**
* Remove a registered global scope.
*
* @param \Illuminate\Database\Eloquent\Scope|string $scope
* @return $this
*/
public function withoutGlobalScope($scope)
{
if (! is_string($scope)) {
$scope = get_class($scope);
}
unset($this->scopes[$scope]);
$this->removedScopes[] = $scope;
return $this;
}
/**
* Remove all or passed registered global scopes.
*
* @param array|null $scopes
* @return $this
*/
public function withoutGlobalScopes(array $scopes = null)
{
if (is_array($scopes)) {
foreach ($scopes as $scope) {
$this->withoutGlobalScope($scope);
}
} else {
$this->scopes = [];
}
return $this;
}
/**
* Get an array of global scopes that were removed from the query.
*
* @return array
*/
public function removedScopes()
{
return $this->removedScopes;
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKey($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '=', $id);
}
/**
* Add a where clause on the primary key to the query.
*
* @param mixed $id
* @return $this
*/
public function whereKeyNot($id)
{
if (is_array($id) || $id instanceof Arrayable) {
$this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);
return $this;
}
return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
}
/**
* Add a basic where clause to the query.
*
* @param string|array|\Closure $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
if ($column instanceof Closure) {
$column($query = $this->model->newModelQuery());
$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
} else {
$this->query->where(...func_get_args());
}
return $this;
}
/**
* Add an "or where" clause to the query.
*
* @param \Closure|array|string $column
* @param string $operator
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function orWhere($column, $operator = null, $value = null)
{
list($value, $operator) = $this->query->prepareValueAndOperator(
$value, $operator, func_num_args() == 2
);
return $this->where($column, $operator, $value, 'or');
}
/**
* Create a collection of models from plain arrays.
*
* @param array $items
* @return \Illuminate\Database\Eloquent\Collection
*/
public function hydrate(array $items)
{
$instance = $this->newModelInstance();
return $instance->newCollection(array_map(function ($item) use ($instance) {
return $instance->newFromBuilder($item);
}, $items));
}
/**
* Create a collection of models from a raw query.
*
* @param string $query
* @param array $bindings
* @return \Illuminate\Database\Eloquent\Collection
*/
public function fromQuery($query, $bindings = [])
{
return $this->hydrate(
$this->query->getConnection()->select($query, $bindings)
);
}
/**
* Find a model by its primary key.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
*/
public function find($id, $columns = ['*'])
{
if (is_array($id) || $id instanceof Arrayable) {
return $this->findMany($id, $columns);
}
return $this->whereKey($id)->first($columns);
}
/**
* Find multiple models by their primary keys.
*
* @param \Illuminate\Contracts\Support\Arrayable|array $ids
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findMany($ids, $columns = ['*'])
{
if (empty($ids)) {
return $this->model->newCollection();
}
return $this->whereKey($ids)->get($columns);
}
/**
* Find a model by its primary key or throw an exception.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function findOrFail($id, $columns = ['*'])
{
$result = $this->find($id, $columns);
if (is_array($id)) {
if (count($result) == count(array_unique($id))) {
return $result;
}
} elseif (! is_null($result)) {
return $result;
}
throw (new ModelNotFoundException)->setModel(
get_class($this->model), $id
);
}
/**
* Find a model by its primary key or return fresh model instance.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model
*/
public function findOrNew($id, $columns = ['*'])
{
if (! is_null($model = $this->find($id, $columns))) {
return $model;
}
return $this->newModelInstance();
}
/**
* Get the first record matching the attributes or instantiate it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrNew(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return $this->newModelInstance($attributes + $values);
}
/**
* Get the first record matching the attributes or create it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
/**
* Execute the query and get the first result or throw an exception.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|static
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function firstOrFail($columns = ['*'])
{
if (! is_null($model = $this->first($columns))) {
return $model;
}
throw (new ModelNotFoundException)->setModel(get_class($this->model));
}
/**
* Execute the query and get the first result or call a callback.
*
* @param \Closure|array $columns
* @param \Closure|null $callback
* @return \Illuminate\Database\Eloquent\Model|static|mixed
*/
public function firstOr($columns = ['*'], Closure $callback = null)
{
if ($columns instanceof Closure) {
$callback = $columns;
$columns = ['*'];
}
if (! is_null($model = $this->first($columns))) {
return $model;
}
return call_user_func($callback);
}
/**
* Get a single column's value from the first result of a query.
*
* @param string $column
* @return mixed
*/
public function value($column)
{
if ($result = $this->first([$column])) {
return $result->{$column};
}
}
/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function get($columns = ['*'])
{
$builder = $this->applyScopes();
// If we actually found models we will also eager load any relationships that
// have been specified as needing to be eager loaded, which will solve the
// n+1 query issue for the developers to avoid running a lot of queries.
if (count($models = $builder->getModels($columns)) > 0) {
$models = $builder->eagerLoadRelations($models);
}
return $builder->getModel()->newCollection($models);
}
/**
* Get the hydrated models without eager loading.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model[]
*/
public function getModels($columns = ['*'])
{
return $this->model->hydrate(
$this->query->get($columns)->all()
)->all();
}
/**
* Eager load the relationships for the models.
*
* @param array $models
* @return array
*/
public function eagerLoadRelations(array $models)
{
foreach ($this->eagerLoad as $name => $constraints) {
// For nested eager loads we'll skip loading them here and they will be set as an
// eager load on the query to retrieve the relation so that they will be eager
// loaded on that query, because that is where they get hydrated as models.
if (strpos($name, '.') === false) {
$models = $this->eagerLoadRelation($models, $name, $constraints);
}
}
return $models;
}
/**
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function eagerLoadRelation(array $models, $name, Closure $constraints)
{
// First we will "back up" the existing where conditions on the query so we can
// add our eager constraints. Then we will merge the wheres that were on the
// query back to it in order that any where conditions might be specified.
$relation = $this->getRelation($name);
$relation->addEagerConstraints($models);
$constraints($relation);
// Once we have the results, we just match those back up to their parent models
// using the relationship instance. Then we just return the finished arrays
// of models which have been eagerly hydrated and are readied for return.
return $relation->match(
$relation->initRelation($models, $name),
$relation->getEager(), $name
);
}
/**
* Get the relation instance for the given relation name.
*
* @param string $name
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function getRelation($name)
{
// We want to run a relationship query without any constrains so that we will
// not have to remove these where clauses manually which gets really hacky
// and error prone. We don't want constraints because we add eager ones.
$relation = Relation::noConstraints(function () use ($name) {
try {
return $this->getModel()->newInstance()->$name();
} catch (BadMethodCallException $e) {
throw RelationNotFoundException::make($this->getModel(), $name);
}
});
$nested = $this->relationsNestedUnder($name);
// If there are nested relationships set on the query, we will put those onto
// the query instances so that they can be handled after this relationship
// is loaded. In this way they will all trickle down as they are loaded.
if (count($nested) > 0) {
$relation->getQuery()->with($nested);
}
return $relation;
}
/**
* Get the deeply nested relations for a given top-level relation.
*
* @param string $relation
* @return array
*/
protected function relationsNestedUnder($relation)
{
$nested = [];
// We are basically looking for any relationships that are nested deeper than
// the given top-level relationship. We will just check for any relations
// that start with the given top relations and adds them to our arrays.
foreach ($this->eagerLoad as $name => $constraints) {
if ($this->isNestedUnder($relation, $name)) {
$nested[substr($name, strlen($relation.'.'))] = $constraints;
}
}
return $nested;
}
/**
* Determine if the relationship is nested.
*
* @param string $relation
* @param string $name
* @return bool
*/
protected function isNestedUnder($relation, $name)
{
return Str::contains($name, '.') && Str::startsWith($name, $relation.'.');
}
/**
* Get a generator for the given query.
*
* @return \Generator
*/
public function cursor()
{
foreach ($this->applyScopes()->query->cursor() as $record) {
yield $this->model->newFromBuilder($record);
}
}
/**
* Chunk the results of a query by comparing numeric IDs.
*
* @param int $count
* @param callable $callback
* @param string $column
* @param string|null $alias
* @return bool
*/
public function chunkById($count, callable $callback, $column = null, $alias = null)
{
$column = is_null($column) ? $this->getModel()->getKeyName() : $column;
$alias = is_null($alias) ? $column : $alias;
$lastId = 0;
do {
$clone = clone $this;
// We'll execute the query for the given page and get the results. If there are
// no results we can just break and return from here. When there are results
// we will call the callback with the current chunk of these results here.
$results = $clone->forPageAfterId($count, $lastId, $column)->get();
$countResults = $results->count();
if ($countResults == 0) {
break;
}
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if ($callback($results) === false) {
return false;
}
$lastId = $results->last()->{$alias};
unset($results);
} while ($countResults == $count);
return true;
}
/**
* Add a generic "order by" clause if the query doesn't already have one.
*
* @return void
*/
protected function enforceOrderBy()
{
if (empty($this->query->orders) && empty($this->query->unionOrders)) {
$this->orderBy($this->model->getQualifiedKeyName(), 'asc');
}
}
/**
* Get an array with the values of a given column.
*
* @param string $column
* @param string|null $key
* @return \Illuminate\Support\Collection
*/
public function pluck($column, $key = null)
{
$results = $this->toBase()->pluck($column, $key);
// If the model has a mutator for the requested column, we will spin through
// the results and mutate the values so that the mutated version of these
// columns are returned as you would expect from these Eloquent models.
if (! $this->model->hasGetMutator($column) &&
! $this->model->hasCast($column) &&
! in_array($column, $this->model->getDates())) {
return $results;
}
return $results->map(function ($value) use ($column) {
return $this->model->newFromBuilder([$column => $value])->{$column};
});
}
/**
* Paginate the given query.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*
* @throws \InvalidArgumentException
*/
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Paginate the given query into a simple paginator.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\Paginator
*/
public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
// Next we will set the limit and offset for this query so that when we get the
// results we get the proper section of results. Then, we'll create the full
// paginator instances for these results with the given page and per page.
$this->skip(($page - 1) * $perPage)->take($perPage + 1);
return $this->simplePaginator($this->get($columns), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}
/**
* Save a new model and return the instance. Allow mass-assignment.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public function forceCreate(array $attributes)
{
return $this->model->unguarded(function () use ($attributes) {
return $this->newModelInstance()->create($attributes);
});
}
/**
* Update a record in the database.
*
* @param array $values
* @return int
*/
public function update(array $values)
{
return $this->toBase()->update($this->addUpdatedAtColumn($values));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function increment($column, $amount = 1, array $extra = [])
{
return $this->toBase()->increment(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
public function decrement($column, $amount = 1, array $extra = [])
{
return $this->toBase()->decrement(
$column, $amount, $this->addUpdatedAtColumn($extra)
);
}
/**
* Add the "updated at" column to an array of values.
*
* @param array $values
* @return array
*/
protected function addUpdatedAtColumn(array $values)
{
if (! $this->model->usesTimestamps()) {
return $values;
}
return Arr::add(
$values, $this->model->getUpdatedAtColumn(),
$this->model->freshTimestampString()
);
}
/**
* Delete a record from the database.
*
* @return mixed
*/
public function delete()
{
if (isset($this->onDelete)) {
return call_user_func($this->onDelete, $this);
}
return $this->toBase()->delete();
}
/**
* Run the default delete function on the builder.
*
* Since we do not apply scopes here, the row will actually be deleted.
*
* @return mixed
*/
public function forceDelete()
{
return $this->query->delete();
}
/**
* Register a replacement for the default delete function.
*
* @param \Closure $callback
* @return void
*/
public function onDelete(Closure $callback)
{
$this->onDelete = $callback;
}
/**
* Call the given local model scopes.
*
* @param array $scopes
* @return mixed
*/
public function scopes(array $scopes)
{
$builder = $this;
foreach ($scopes as $scope => $parameters) {
// If the scope key is an integer, then the scope was passed as the value and
// the parameter list is empty, so we will format the scope name and these
// parameters here. Then, we'll be ready to call the scope on the model.
if (is_int($scope)) {
list($scope, $parameters) = [$parameters, []];
}
// Next we'll pass the scope callback to the callScope method which will take
// care of grouping the "wheres" properly so the logical order doesn't get
// messed up when adding scopes. Then we'll return back out the builder.
$builder = $builder->callScope(
[$this->model, 'scope'.ucfirst($scope)],
(array) $parameters
);
}
return $builder;
}
/**
* Apply the scopes to the Eloquent builder instance and return it.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function applyScopes()
{
if (! $this->scopes) {
return $this;
}
$builder = clone $this;
foreach ($this->scopes as $identifier => $scope) {
if (! isset($builder->scopes[$identifier])) {
continue;
}
$builder->callScope(function (Builder $builder) use ($scope) {
// If the scope is a Closure we will just go ahead and call the scope with the
// builder instance. The "callScope" method will properly group the clauses
// that are added to this query so "where" clauses maintain proper logic.
if ($scope instanceof Closure) {
$scope($builder);
}
// If the scope is a scope object, we will call the apply method on this scope
// passing in the builder and the model instance. After we run all of these
// scopes we will return back the builder instance to the outside caller.
if ($scope instanceof Scope) {
$scope->apply($builder, $this->getModel());
}
});
}
return $builder;
}
/**
* Apply the given scope on the current builder instance.
*
* @param callable $scope
* @param array $parameters
* @return mixed
*/
protected function callScope(callable $scope, $parameters = [])
{
array_unshift($parameters, $this);
$query = $this->getQuery();
// We will keep track of how many wheres are on the query before running the
// scope so that we can properly group the added scope constraints in the
// query as their own isolated nested where statement and avoid issues.
$originalWhereCount = is_null($query->wheres)
? 0 : count($query->wheres);
$result = $scope(...array_values($parameters)) ?? $this;
if (count((array) $query->wheres) > $originalWhereCount) {
$this->addNewWheresWithinGroup($query, $originalWhereCount);
}
return $result;
}
/**
* Nest where conditions by slicing them at the given where count.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $originalWhereCount
* @return void
*/
protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount)
{
// Here, we totally remove all of the where clauses since we are going to
// rebuild them as nested queries by slicing the groups of wheres into
// their own sections. This is to prevent any confusing logic order.
$allWheres = $query->wheres;
$query->wheres = [];
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, 0, $originalWhereCount)
);
$this->groupWhereSliceForScope(
$query, array_slice($allWheres, $originalWhereCount)
);
}
/**
* Slice where conditions at the given offset and add them to the query as a nested condition.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $whereSlice
* @return void
*/
protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
{
$whereBooleans = collect($whereSlice)->pluck('boolean');
// Here we'll check if the given subset of where clauses contains any "or"
// booleans and in this case create a nested where expression. That way
// we don't add any unnecessary nesting thus keeping the query clean.
if ($whereBooleans->contains('or')) {
$query->wheres[] = $this->createNestedWhere(
$whereSlice, $whereBooleans->first()
);
} else {
$query->wheres = array_merge($query->wheres, $whereSlice);
}
}
/**
* Create a where array with nested where conditions.
*
* @param array $whereSlice
* @param string $boolean
* @return array
*/
protected function createNestedWhere($whereSlice, $boolean = 'and')
{
$whereGroup = $this->getQuery()->forNestedWhere();
$whereGroup->wheres = $whereSlice;
return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean];
}
/**
* Set the relationships that should be eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function with($relations)
{
$eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
$this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad);
return $this;
}
/**
* Prevent the specified relations from being eager loaded.
*
* @param mixed $relations
* @return $this
*/
public function without($relations)
{
$this->eagerLoad = array_diff_key($this->eagerLoad, array_flip(
is_string($relations) ? func_get_args() : $relations
));
return $this;
}
/**
* Create a new instance of the model being queried.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function newModelInstance($attributes = [])
{
return $this->model->newInstance($attributes)->setConnection(
$this->query->getConnection()->getName()
);
}
/**
* Parse a list of relations into individuals.
*
* @param array $relations
* @return array
*/
protected function parseWithRelations(array $relations)
{
$results = [];
foreach ($relations as $name => $constraints) {
// If the "relation" value is actually a numeric key, we can assume that no
// constraints have been specified for the eager load and we'll just put
// an empty Closure with the loader so that we can treat all the same.
if (is_numeric($name)) {
$name = $constraints;
list($name, $constraints) = Str::contains($name, ':')
? $this->createSelectWithConstraint($name)
: [$name, function () {
//
}];
}
// We need to separate out any nested includes. Which allows the developers
// to load deep relationships using "dots" without stating each level of
// the relationship with its own key in the array of eager load names.
$results = $this->addNestedWiths($name, $results);
$results[$name] = $constraints;
}
return $results;
}
/**
* Create a constraint to select the given columns for the relation.
*
* @param string $name
* @return array
*/
protected function createSelectWithConstraint($name)
{
return [explode(':', $name)[0], function ($query) use ($name) {
$query->select(explode(',', explode(':', $name)[1]));
}];
}
/**
* Parse the nested relationships in a relation.
*
* @param string $name
* @param array $results
* @return array
*/
protected function addNestedWiths($name, $results)
{
$progress = [];
// If the relation has already been set on the result array, we will not set it
// again, since that would override any constraints that were already placed
// on the relationships. We will only set the ones that are not specified.
foreach (explode('.', $name) as $segment) {
$progress[] = $segment;
if (! isset($results[$last = implode('.', $progress)])) {
$results[$last] = function () {
//
};
}
}
return $results;
}
/**
* Get the underlying query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getQuery()
{
return $this->query;
}
/**
* Set the underlying query builder instance.
*
* @param \Illuminate\Database\Query\Builder $query
* @return $this
*/
public function setQuery($query)
{
$this->query = $query;
return $this;
}
/**
* Get a base query builder instance.
*
* @return \Illuminate\Database\Query\Builder
*/
public function toBase()
{
return $this->applyScopes()->getQuery();
}
/**
* Get the relationships being eagerly loaded.
*
* @return array
*/
public function getEagerLoads()
{
return $this->eagerLoad;
}
/**
* Set the relationships being eagerly loaded.
*
* @param array $eagerLoad
* @return $this
*/
public function setEagerLoads(array $eagerLoad)
{
$this->eagerLoad = $eagerLoad;
return $this;
}
/**
* Get the model instance being queried.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function getModel()
{
return $this->model;
}
/**
* Set a model instance for the model being queried.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return $this
*/
public function setModel(Model $model)
{
$this->model = $model;
$this->query->from($model->getTable());
return $this;
}
/**
* Qualify the given column name by the model's table.
*
* @param string $column
* @return string
*/
public function qualifyColumn($column)
{
return $this->model->qualifyColumn($column);
}
/**
* Get the given macro by name.
*
* @param string $name
* @return \Closure
*/
public function getMacro($name)
{
return Arr::get($this->localMacros, $name);
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if ($method === 'macro') {
$this->localMacros[$parameters[0]] = $parameters[1];
return;
}
if (isset($this->localMacros[$method])) {
array_unshift($parameters, $this);
return $this->localMacros[$method](...$parameters);
}
if (isset(static::$macros[$method])) {
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
return $this->callScope([$this->model, $scope], $parameters);
}
if (in_array($method, $this->passthru)) {
return $this->toBase()->{$method}(...$parameters);
}
$this->query->{$method}(...$parameters);
return $this;
}
/**
* Dynamically handle calls into the query instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public static function __callStatic($method, $parameters)
{
if ($method === 'macro') {
static::$macros[$parameters[0]] = $parameters[1];
return;
}
if (! isset(static::$macros[$method])) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
/**
* Force a clone of the underlying query builder when cloning.
*
* @return void
*/
public function __clone()
{
$this->query = clone $this->query;
}
}
| drthomas21/WordPress_Tutorial | community_htdocs/vendor/illuminate/database/Eloquent/Builder.php | PHP | apache-2.0 | 37,905 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user);
Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user);
Task<bool> MarkDoneAsync(Guid id, ApplicationUser user);
}
} | nqdien/littleaspnetcorebook | Services/ITodoItemService.cs | C# | apache-2.0 | 420 |
/*
* 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.ivy.core.pack;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ivy.util.FileUtil;
/**
* Packaging which handle OSGi bundles with inner packed jar
*/
public class OsgiBundlePacking extends ZipPacking {
private static final String[] NAMES = {"bundle"};
@Override
public String[] getNames() {
return NAMES;
}
@Override
protected void writeFile(InputStream zip, File f) throws IOException {
// XXX maybe we should only unpack file listed by the 'Bundle-ClassPath' MANIFEST header ?
if (f.getName().endsWith(".jar.pack.gz")) {
zip = FileUtil.unwrapPack200(zip);
f = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - 8));
}
super.writeFile(zip, f);
}
}
| jaikiran/ant-ivy | src/java/org/apache/ivy/core/pack/OsgiBundlePacking.java | Java | apache-2.0 | 1,656 |
package fr.openwide.core.wicket.more.markup.html.feedback;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
public abstract class AbstractFeedbackPanel extends Panel {
private static final long serialVersionUID = 8440891357292721078L;
private static final int[] ERROR_MESSAGE_LEVELS = {
FeedbackMessage.FATAL,
FeedbackMessage.ERROR,
FeedbackMessage.WARNING,
FeedbackMessage.SUCCESS,
FeedbackMessage.INFO,
FeedbackMessage.DEBUG,
FeedbackMessage.UNDEFINED
};
private static final String[] ERROR_MESSAGE_LEVEL_NAMES = {
"FATAL",
"ERROR",
"WARNING",
"SUCCESS",
"INFO",
"DEBUG",
"UNDEFINED"
};
private List<FeedbackPanel> feedbackPanels = new ArrayList<FeedbackPanel>();
public AbstractFeedbackPanel(String id, MarkupContainer container) {
super(id);
int i = 0;
for(int level: ERROR_MESSAGE_LEVELS) {
FeedbackPanel f = getFeedbackPanel(ERROR_MESSAGE_LEVEL_NAMES[i] + "feedbackPanel", level, container);
feedbackPanels.add(f);
add(f);
i++;
}
}
public abstract FeedbackPanel getFeedbackPanel(String id, int level, MarkupContainer container);
}
| openwide-java/owsi-core-parent | owsi-core/owsi-core-components/owsi-core-component-wicket-more/src/main/java/fr/openwide/core/wicket/more/markup/html/feedback/AbstractFeedbackPanel.java | Java | apache-2.0 | 1,314 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "reader";
$route['sitemap.xml'] = "reader/sitemap";
$route['rss.xml'] = "reader/feeds";
$route['atom.xml'] = "reader/feeds/atom";
$route['admin'] = "admin/series";
$route['admin/series/series/(:any)'] = "admin/series/serie/$1";
$route['account'] = "account/index/profile";
$route['account/profile'] = "account/index/profile";
$route['account/teams'] = "account/index/teams";
$route['account/leave_team/(:any)'] = "account/index/leave_team/$1";
$route['account/request/(:any)'] = "account/index/request/$1";
$route['account/leave_leadership/(:any)'] = "account/index/leave_leadership/$1";
$route['reader/list'] = 'reader/lista';
$route['reader/list/(:num)'] = 'reader/lista/$1';
$route['admin/members/members'] = 'admin/members/membersa';
// added for compatibility on upgrade 0.8.1 -> 0.8.2 on 30/09/2011
$route['admin/upgrade'] = 'admin/system/upgrade';
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | woxxy/FoOlSlide | application/config/routes.php | PHP | apache-2.0 | 2,388 |
/*
* EditorMouseMenu.java
*
* Created on March 21, 2007, 10:34 AM; Updated May 29, 2007
*
* Copyright 2007 Grotto Networking
*/
package Samples.MouseMenu;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
/**
* Illustrates the use of custom edge and vertex classes in a graph editing application.
* Demonstrates a new graph mouse plugin for bringing up popup menus for vertices and
* edges.
* @author Dr. Greg M. Bernstein
*/
public class EditorMouseMenu {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Editing and Mouse Menu Demo");
SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> g =
new SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge>();
// Layout<V, E>, VisualizationViewer<V,E>
// Map<GraphElements.MyVertex,Point2D> vertexLocations = new HashMap<GraphElements.MyVertex, Point2D>();
Layout<GraphElements.MyVertex, GraphElements.MyEdge> layout = new StaticLayout(g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge> vv =
new VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Show vertex and edge labels
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
// Create a graph mouse and add it to the visualization viewer
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
GraphElements.MyVertexFactory.getInstance(),
GraphElements.MyEdgeFactory.getInstance());
// Set some defaults for the Edges...
GraphElements.MyEdgeFactory.setDefaultCapacity(192.0);
GraphElements.MyEdgeFactory.setDefaultWeight(5.0);
// Trying out our new popup menu mouse plugin...
PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
// Add some popup menus for the edges and vertices to our mouse plugin.
JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();
myPlugin.setEdgePopup(edgeMenu);
myPlugin.setVertexPopup(vertexMenu);
gm.remove(gm.getPopupEditingPlugin()); // Removes the existing popup editing plugin
gm.add(myPlugin); // Add our new plugin to the mouse
vv.setGraphMouse(gm);
//JFrame frame = new JFrame("Editing and Mouse Menu Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
// Let's add a menu for changing mouse modes
JMenuBar menuBar = new JMenuBar();
JMenu modeMenu = gm.getModeMenu();
modeMenu.setText("Mouse Mode");
modeMenu.setIcon(null); // I'm using this in a main menu
modeMenu.setPreferredSize(new Dimension(80,20)); // Change the size so I can see the text
menuBar.add(modeMenu);
frame.setJMenuBar(menuBar);
gm.setMode(ModalGraphMouse.Mode.EDITING); // Start off in editing mode
frame.pack();
frame.setVisible(true);
}
}
| ksotala/BayesGame | BayesGame/src/Samples/MouseMenu/EditorMouseMenu.java | Java | apache-2.0 | 3,984 |
package ru.job4j.max;
/**
*Класс помогает узнать, какое из двух чисел больше.
*@author ifedorenko
*@since 14.08.2017
*@version 1
*/
public class Max {
/**
*Возвращает большее число из двух.
*@param first содержит первое число
*@param second содержит второе число
*@return Большее из двух
*/
public int max(int first, int second) {
return first > second ? first : second;
}
/**
*Возвращает большее число из трех.
*@param first содержит первое число
*@param second содержит второе число
*@param third содержит третье число
*@return Большее из трех
*/
public int max(int first, int second, int third) {
return max(first, max(second, third));
}
} | fr3anthe/ifedorenko | 1.1-Base/src/main/java/ru/job4j/max/Max.java | Java | apache-2.0 | 887 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.docsearch.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
import org.kuali.rice.kew.docsearch.dao.DocumentSearchDAO;
import org.kuali.rice.kew.impl.document.search.DocumentSearchGenerator;
import org.kuali.rice.kew.util.PerformanceLogger;
import org.kuali.rice.krad.util.KRADConstants;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/**
* Spring JdbcTemplate implementation of DocumentSearchDAO
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public class DocumentSearchDAOJdbcImpl implements DocumentSearchDAO {
public static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentSearchDAOJdbcImpl.class);
private static final int DEFAULT_FETCH_MORE_ITERATION_LIMIT = 10;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = new TransactionAwareDataSourceProxy(dataSource);
}
@Override
public DocumentSearchResults.Builder findDocuments(final DocumentSearchGenerator documentSearchGenerator, final DocumentSearchCriteria criteria, final boolean criteriaModified, final List<RemotableAttributeField> searchFields) {
final int maxResultCap = getMaxResultCap(criteria);
try {
final JdbcTemplate template = new JdbcTemplate(dataSource);
return template.execute(new ConnectionCallback<DocumentSearchResults.Builder>() {
@Override
public DocumentSearchResults.Builder doInConnection(final Connection con) throws SQLException {
final Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
final int fetchIterationLimit = getFetchMoreIterationLimit();
final int fetchLimit = fetchIterationLimit * maxResultCap;
statement.setFetchSize(maxResultCap + 1);
statement.setMaxRows(fetchLimit + 1);
PerformanceLogger perfLog = new PerformanceLogger();
String sql = documentSearchGenerator.generateSearchSql(criteria, searchFields);
perfLog.log("Time to generate search sql from documentSearchGenerator class: " + documentSearchGenerator
.getClass().getName(), true);
LOG.info("Executing document search with statement max rows: " + statement.getMaxRows());
LOG.info("Executing document search with statement fetch size: " + statement.getFetchSize());
perfLog = new PerformanceLogger();
final ResultSet rs = statement.executeQuery(sql);
try {
perfLog.log("Time to execute doc search database query.", true);
final Statement searchAttributeStatement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
return documentSearchGenerator.processResultSet(criteria, criteriaModified, searchAttributeStatement, rs, maxResultCap, fetchLimit);
} finally {
try {
searchAttributeStatement.close();
} catch (SQLException e) {
LOG.warn("Could not close search attribute statement.");
}
}
} finally {
try {
rs.close();
} catch (SQLException e) {
LOG.warn("Could not close result set.");
}
}
} finally {
try {
statement.close();
} catch (SQLException e) {
LOG.warn("Could not close statement.");
}
}
}
});
} catch (DataAccessException dae) {
String errorMsg = "DataAccessException: " + dae.getMessage();
LOG.error("getList() " + errorMsg, dae);
throw new RuntimeException(errorMsg, dae);
} catch (Exception e) {
String errorMsg = "LookupException: " + e.getMessage();
LOG.error("getList() " + errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
}
/**
* Returns the maximum number of results that should be returned from the document search.
*
* @param criteria the criteria in which to check for a max results value
* @return the maximum number of results that should be returned from a document search
*/
public int getMaxResultCap(DocumentSearchCriteria criteria) {
int systemLimit = KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP;
String resultCapValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_RESULT_CAP);
if (StringUtils.isNotBlank(resultCapValue)) {
try {
int configuredLimit = Integer.parseInt(resultCapValue);
if (configuredLimit <= 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " was less than or equal to zero. Please use a positive integer.");
} else {
systemLimit = configuredLimit;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " is not a valid number. Value was " + resultCapValue + ". Using default: " + KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP);
}
}
int maxResults = systemLimit;
if (criteria.getMaxResults() != null) {
int criteriaLimit = criteria.getMaxResults().intValue();
if (criteriaLimit > systemLimit) {
LOG.warn("Result set cap of " + criteriaLimit + " is greater than system value of " + systemLimit);
} else {
if (criteriaLimit < 0) {
LOG.warn("Criteria results limit was less than zero.");
criteriaLimit = 0;
}
maxResults = criteriaLimit;
}
}
return maxResults;
}
public int getFetchMoreIterationLimit() {
int fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
String fetchMoreLimitValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT);
if (!StringUtils.isBlank(fetchMoreLimitValue)) {
try {
fetchMoreLimit = Integer.parseInt(fetchMoreLimitValue);
if (fetchMoreLimit < 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " was less than zero. Please use a value greater than or equal to zero.");
fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " is not a valid number. Value was " + fetchMoreLimitValue);
}
}
return fetchMoreLimit;
}
}
| ua-eas/ua-rice-2.1.9 | impl/src/main/java/org/kuali/rice/kew/docsearch/dao/impl/DocumentSearchDAOJdbcImpl.java | Java | apache-2.0 | 8,999 |
/*
* Copyright 2016 Alexander Severgin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.alpinweiss.filegen.util.generator.impl;
import eu.alpinweiss.filegen.model.FieldDefinition;
import eu.alpinweiss.filegen.model.FieldType;
import eu.alpinweiss.filegen.util.wrapper.AbstractDataWrapper;
import eu.alpinweiss.filegen.util.generator.FieldGenerator;
import eu.alpinweiss.filegen.util.vault.ParameterVault;
import eu.alpinweiss.filegen.util.vault.ValueVault;
import org.apache.commons.lang.StringUtils;
import java.util.concurrent.ThreadLocalRandom;
/**
* {@link AutoNumberGenerator}.
*
* @author Aleksandrs.Severgins | <a href="http://alpinweiss.eu">SIA Alpinweiss</a>
*/
public class AutoNumberGenerator implements FieldGenerator {
private final FieldDefinition fieldDefinition;
private int startNum;
public AutoNumberGenerator(FieldDefinition fieldDefinition) {
this.fieldDefinition = fieldDefinition;
final String pattern = this.fieldDefinition.getPattern();
if (!pattern.isEmpty()) {
startNum = Integer.parseInt(pattern);
}
}
@Override
public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator, ValueVault valueVault) {
valueVault.storeValue(new IntegerDataWrapper() {
@Override
public Double getNumberValue() {
int value = startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber()) + parameterVault.iterationNumber();
return new Double(value);
}
});
}
private class IntegerDataWrapper extends AbstractDataWrapper {
@Override
public FieldType getFieldType() {
return FieldType.INTEGER;
}
}
}
| alpinweiss/filegen | src/main/java/eu/alpinweiss/filegen/util/generator/impl/AutoNumberGenerator.java | Java | apache-2.0 | 2,280 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.provider;
import java.util.Collection;
import java.util.List;
import net.opengis.gml.FeatureStyleType;
import net.opengis.gml.GmlFactory;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link net.opengis.gml.FeatureStyleType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FeatureStyleTypeItemProvider
extends AbstractGMLTypeItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureStyleTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addFeatureConstraintPropertyDescriptor(object);
addBaseTypePropertyDescriptor(object);
addFeatureTypePropertyDescriptor(object);
addQueryGrammarPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Feature Constraint feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureConstraintPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureConstraint_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureConstraint_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureConstraint(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Base Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addBaseTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_baseType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_baseType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_BaseType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Feature Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Query Grammar feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addQueryGrammarPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_queryGrammar_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_queryGrammar_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_QueryGrammar(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle());
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns FeatureStyleType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FeatureStyleType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((FeatureStyleType)object).getId();
return label == null || label.length() == 0 ?
getString("_UI_FeatureStyleType_type") :
getString("_UI_FeatureStyleType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(FeatureStyleType.class)) {
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_CONSTRAINT:
case GmlPackage.FEATURE_STYLE_TYPE__BASE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__QUERY_GRAMMAR:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case GmlPackage.FEATURE_STYLE_TYPE__GEOMETRY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__TOPOLOGY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__LABEL_STYLE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle(),
GmlFactory.eINSTANCE.createGeometryStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle(),
GmlFactory.eINSTANCE.createTopologyStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle(),
GmlFactory.eINSTANCE.createLabelStylePropertyType()));
}
/**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
childFeature = entry.getEStructuralFeature();
childObject = entry.getValue();
}
boolean qualify =
childFeature == GmlPackage.eINSTANCE.getAbstractGMLType_Name() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CoordinateOperationName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CsName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_DatumName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_EllipsoidName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_GroupName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MeridianName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MethodName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_ParameterName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_SrsName();
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
}
}
| markus1978/citygml4emf | de.hub.citygml.emf.ecore.edit/src/net/opengis/gml/provider/FeatureStyleTypeItemProvider.java | Java | apache-2.0 | 10,661 |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GKE nodes service account permissions for logging.
The service account used by GKE nodes should have the logging.logWriter
role, otherwise ingestion of logs won't work.
"""
from gcpdiag import lint, models
from gcpdiag.queries import gke, iam
ROLE = 'roles/logging.logWriter'
def prefetch_rule(context: models.Context):
# Make sure that we have the IAM policy in cache.
project_ids = {c.project_id for c in gke.get_clusters(context).values()}
for pid in project_ids:
iam.get_project_policy(pid)
def run_rule(context: models.Context, report: lint.LintReportRuleInterface):
# Find all clusters with logging enabled.
clusters = gke.get_clusters(context)
iam_policy = iam.get_project_policy(context.project_id)
if not clusters:
report.add_skipped(None, 'no clusters found')
for _, c in sorted(clusters.items()):
if not c.has_logging_enabled():
report.add_skipped(c, 'logging disabled')
else:
# Verify service-account permissions for every nodepool.
for np in c.nodepools:
sa = np.service_account
if not iam.is_service_account_enabled(sa, context.project_id):
report.add_failed(np, f'service account disabled or deleted: {sa}')
elif not iam_policy.has_role_permissions(f'serviceAccount:{sa}', ROLE):
report.add_failed(np, f'service account: {sa}\nmissing role: {ROLE}')
else:
report.add_ok(np)
| GoogleCloudPlatform/gcpdiag | gcpdiag/lint/gke/err_2021_001_logging_perm.py | Python | apache-2.0 | 1,986 |
package sarama
// ApiVersionsRequest ...
type ApiVersionsRequest struct{}
func (a *ApiVersionsRequest) encode(pe packetEncoder) error {
return nil
}
func (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {
return nil
}
func (a *ApiVersionsRequest) key() int16 {
return 18
}
func (a *ApiVersionsRequest) version() int16 {
return 0
}
func (a *ApiVersionsRequest) headerVersion() int16 {
return 1
}
func (a *ApiVersionsRequest) requiredVersion() KafkaVersion {
return V0_10_0_0
}
| trivago/gollum | vendor/github.com/Shopify/sarama/api_versions_request.go | GO | apache-2.0 | 516 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.neptune.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/neptune-2014-10-31/RemoveRoleFromDBCluster" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveRoleFromDBClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemoveRoleFromDBClusterResult == false)
return false;
RemoveRoleFromDBClusterResult other = (RemoveRoleFromDBClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public RemoveRoleFromDBClusterResult clone() {
try {
return (RemoveRoleFromDBClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-neptune/src/main/java/com/amazonaws/services/neptune/model/RemoveRoleFromDBClusterResult.java | Java | apache-2.0 | 2,392 |
using System.Collections.Generic;
namespace Microsoft.Xna.Framework.Graphics
{
internal partial class DXConstantBufferData
{
public string Name { get; private set; }
public int Size { get; private set; }
public List<int> ParameterIndex { get; private set; }
public List<int> ParameterOffset { get; private set; }
public List<DXEffectObject.d3dx_parameter> Parameters { get; private set; }
public bool SameAs(DXConstantBufferData other)
{
// If the names of the constant buffers don't
// match then consider them different right off
// the bat... even if their parameters are the same.
if (Name != other.Name)
return false;
// Do we have the same count of parameters and size?
if ( Size != other.Size ||
Parameters.Count != other.Parameters.Count)
return false;
// Compare the parameters themselves.
for (var i = 0; i < Parameters.Count; i++)
{
var p1 = Parameters[i];
var p2 = other.Parameters[i];
// Check the importaint bits.
if ( p1.name != p2.name ||
p1.rows != p2.rows ||
p1.columns != p2.columns ||
p1.class_ != p2.class_ ||
p1.type != p2.type ||
p1.bufferOffset != p2.bufferOffset)
return false;
}
// These are equal.
return true;
}
}
}
| jonathanpeppers/MonoGameOrientation | MonoGame/Tools/2MGFX/DXConstantBufferData.cs | C# | apache-2.0 | 1,654 |
package ru.istolbov;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author istolbov
* @version $Id$
*/
public class TurnTest {
/**
* Test turn back array.
*/
@Test
public void whenWeTurnBackArray() {
final int[] targetArray = new int[] {5, 4, 3, 2, 1};
final int[] testArray = new int[] {1, 2, 3, 4, 5};
final Turn turn = new Turn();
final int[] resultArray = turn.back(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test sort.
*/
@Test
public void whenWeSortArray() {
final int[] targetArray = new int[] {1, 2, 3, 4, 5};
final int[] testArray = new int[] {5, 3, 4, 1, 2};
final Turn turn = new Turn();
final int[] resultArray = turn.sort(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test rotate.
*/
@Test
public void whenWeRotateArray() {
final int[][] targetArray = new int[][] {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}};
final int[][] testArray = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
final Turn turn = new Turn();
final int[][] resultArray = turn.rotate(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test duplicateDelete.
*/
@Test
public void whenWeDuplicateDeleteInArray() {
final String[] targetArray = new String[] {"Привет", "Мир", "Май"};
final String[] testArray = new String[] {"Привет", "Привет", "Мир", "Привет", "Май", "Май", "Мир"};
final Turn turn = new Turn();
final String[] resultArray = turn.duplicateDelete(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test join.
*/
@Test
public void whenWeJoinArrays() {
final int[] firstTestArray = new int[] {1, 3, 5, 7, 9};
final int[] secondTestArray = new int[] {2, 4, 6, 8, 10};
final int[] targetArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final Turn turn = new Turn();
final int[] resultArray = turn.join(firstTestArray, secondTestArray);
assertThat(resultArray, is(targetArray));
}
} | istolbov/i_stolbov | chapter_001/src/test/java/ru/istolbov/TurnTest.java | Java | apache-2.0 | 2,196 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("jd")]
[assembly: AssemblyProduct("ConsoleApplication2")]
[assembly: AssemblyCopyright("Copyright © jd 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("54da768a-cc04-48a7-892b-57549b90159e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| singhjaideep/ado-net-segfault | ConsoleApplication2/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,454 |
package javay.test.security;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* DES安全编码组件
*
* <pre>
* 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
* </pre>
*
*/
public abstract class DESCoder extends Coder {
/**
* ALGORITHM 算法 <br>
* 可替换为以下任意一种算法,同时key值的size相应改变。
*
* <pre>
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* </pre>
*
* 在Key toKey(byte[] key)方法中使用下述代码
* <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换
* <code>
* DESKeySpec dks = new DESKeySpec(key);
* SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
* SecretKey secretKey = keyFactory.generateSecret(dks);
* </code>
*/
public static final String ALGORITHM = "DES";
/**
* 转换密钥<br>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
// SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}
/**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 生成密钥
*
* @return
* @throws Exception
*/
public static String initKey() throws Exception {
return initKey(null);
}
/**
* 生成密钥
*
* @param seed
* @return
* @throws Exception
*/
public static String initKey(String seed) throws Exception {
SecureRandom secureRandom = null;
if (seed != null) {
secureRandom = new SecureRandom(decryptBASE64(seed));
} else {
secureRandom = new SecureRandom();
}
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
}
| dubenju/javay | src/java/javay/test/security/DESCoder.java | Java | apache-2.0 | 4,047 |
/*
* Copyright 2016 Yu Sheng. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ysheng.auth.model.api;
/**
* Defines the grant types.
*/
public enum GrantType {
AUTHORIZATION_CODE,
IMPLICIT,
PASSWORD,
CLIENT_CREDENTIALS
}
| zeelichsheng/auth | auth-model/src/main/java/com/ysheng/auth/model/api/GrantType.java | Java | apache-2.0 | 769 |
/* jshint sub: true */
/* global exports: true */
'use strict';
// //////////////////////////////////////////////////////////////////////////////
// / @brief node-request-style HTTP requests
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2015 triAGENS GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// / http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Alan Plum
// / @author Copyright 2015, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
const internal = require('internal');
const Buffer = require('buffer').Buffer;
const extend = require('lodash').extend;
const httperr = require('http-errors');
const is = require('@arangodb/is');
const querystring = require('querystring');
const qs = require('qs');
const url = require('url');
class Response {
throw (msg) {
if (this.status >= 400) {
throw Object.assign(
httperr(this.status, msg || this.message),
{details: this}
);
}
}
constructor (res, encoding, json) {
this.status = this.statusCode = res.code;
this.message = res.message;
this.headers = res.headers ? res.headers : {};
this.body = this.rawBody = res.body;
if (this.body && encoding !== null) {
this.body = this.body.toString(encoding || 'utf-8');
if (json) {
try {
this.json = JSON.parse(this.body);
} catch (e) {
this.json = undefined;
}
}
}
}
}
function querystringify (query, useQuerystring) {
if (!query) {
return '';
}
if (typeof query === 'string') {
return query.charAt(0) === '?' ? query.slice(1) : query;
}
return (useQuerystring ? querystring : qs).stringify(query)
.replace(/[!'()*]/g, function (c) {
// Stricter RFC 3986 compliance
return '%' + c.charCodeAt(0).toString(16);
});
}
function request (req) {
if (typeof req === 'string') {
req = {url: req, method: 'GET'};
}
let path = req.url || req.uri;
if (!path) {
throw new Error('Request URL must not be empty.');
}
let pathObj = typeof path === 'string' ? url.parse(path) : path;
if (pathObj.auth) {
let auth = pathObj.auth.split(':');
req = extend({
auth: {
username: decodeURIComponent(auth[0]),
password: decodeURIComponent(auth[1])
}
}, req);
delete pathObj.auth;
}
let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring);
if (query) {
pathObj.search = query;
}
path = url.format(pathObj);
let contentType;
let body = req.body;
if (req.json) {
body = JSON.stringify(body);
contentType = 'application/json';
} else if (typeof body === 'string') {
contentType = 'text/plain; charset=utf-8';
} else if (typeof body === 'object' && body instanceof Buffer) {
contentType = 'application/octet-stream';
} else if (!body) {
if (req.form) {
contentType = 'application/x-www-form-urlencoded';
body = typeof req.form === 'string' ? req.form : querystringify(req.form, req.useQuerystring);
} else if (req.formData) {
// contentType = 'multipart/form-data'
// body = formData(req.formData)
throw new Error('Multipart form encoding is currently not supported.');
} else if (req.multipart) {
// contentType = 'multipart/related'
// body = multipart(req.multipart)
throw new Error('Multipart encoding is currently not supported.');
}
}
const headers = {};
if (contentType) {
headers['content-type'] = contentType;
}
if (req.headers) {
Object.keys(req.headers).forEach(function (name) {
headers[name.toLowerCase()] = req.headers[name];
});
}
if (req.auth) {
headers['authorization'] = ( // eslint-disable-line dot-notation
req.auth.bearer ?
'Bearer ' + req.auth.bearer :
'Basic ' + new Buffer(
req.auth.username + ':' +
req.auth.password
).toString('base64')
);
}
let options = {
method: (req.method || 'get').toUpperCase(),
headers: headers,
returnBodyAsBuffer: true,
returnBodyOnError: req.returnBodyOnError !== false
};
if (is.existy(req.timeout)) {
options.timeout = req.timeout;
}
if (is.existy(req.followRedirect)) {
options.followRedirects = req.followRedirect; // [sic] node-request compatibility
}
if (is.existy(req.maxRedirects)) {
options.maxRedirects = req.maxRedirects;
} else {
options.maxRedirects = 10;
}
if (req.sslProtocol) {
options.sslProtocol = req.sslProtocol;
}
let result = internal.download(path, body, options);
return new Response(result, req.encoding, req.json);
}
exports = request;
exports.request = request;
exports.Response = Response;
['delete', 'get', 'head', 'patch', 'post', 'put']
.forEach(function (method) {
exports[method.toLowerCase()] = function (url, options) {
if (typeof url === 'object') {
options = url;
url = undefined;
} else if (typeof url === 'string') {
options = extend({}, options, {url: url});
}
return request(extend({method: method.toUpperCase()}, options));
};
});
module.exports = exports;
| baslr/ArangoDB | js/common/modules/@arangodb/request.js | JavaScript | apache-2.0 | 5,781 |
/// <reference path="../apimanPlugin.ts"/>
/// <reference path="../services.ts"/>
module Apiman {
export var UserRedirectController = _module.controller("Apiman.UserRedirectController",
['$q', '$scope', '$location', 'PageLifecycle', '$routeParams',
($q, $scope, $location, PageLifecycle, $routeParams) => {
PageLifecycle.loadPage('UserRedirect', undefined, undefined, $scope, function() {
PageLifecycle.forwardTo('/users/{0}/orgs', $routeParams.user);
});
}])
}
| kunallimaye/apiman | manager/ui/hawtio/plugins/api-manager/ts/user/user.ts | TypeScript | apache-2.0 | 528 |
#ifndef _TCUX11_HPP
#define _TCUX11_HPP
/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 utilities.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "gluRenderConfig.hpp"
#include "gluPlatform.hpp"
#include "deMutex.hpp"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
namespace tcu
{
namespace x11
{
enum
{
DEFAULT_WINDOW_WIDTH = 400,
DEFAULT_WINDOW_HEIGHT = 300
};
class EventState
{
public:
EventState (void);
virtual ~EventState (void);
void setQuitFlag (bool quit);
bool getQuitFlag (void);
protected:
de::Mutex m_mutex;
bool m_quit;
private:
EventState (const EventState&);
EventState& operator= (const EventState&);
};
class DisplayBase
{
public:
DisplayBase (EventState& platform);
virtual ~DisplayBase (void);
virtual void processEvents (void) = 0;
protected:
EventState& m_eventState;
private:
DisplayBase (const DisplayBase&);
DisplayBase& operator= (const DisplayBase&);
};
class WindowBase
{
public:
WindowBase (void);
virtual ~WindowBase (void);
virtual void setVisibility (bool visible) = 0;
virtual void processEvents (void) = 0;
virtual DisplayBase& getDisplay (void) = 0;
virtual void getDimensions (int* width, int* height) const = 0;
virtual void setDimensions (int width, int height) = 0;
protected:
bool m_visible;
private:
WindowBase (const WindowBase&);
WindowBase& operator= (const WindowBase&);
};
class XlibDisplay : public DisplayBase
{
public:
XlibDisplay (EventState& platform, const char* name);
virtual ~XlibDisplay (void);
::Display* getXDisplay (void) { return m_display; }
Atom getDeleteAtom (void) { return m_deleteAtom; }
::Visual* getVisual (VisualID visualID);
bool getVisualInfo (VisualID visualID, XVisualInfo& dst);
void processEvents (void);
void processEvent (XEvent& event);
protected:
::Display* m_display;
Atom m_deleteAtom;
private:
XlibDisplay (const XlibDisplay&);
XlibDisplay& operator= (const XlibDisplay&);
};
class XlibWindow : public WindowBase
{
public:
XlibWindow (XlibDisplay& display, int width, int height,
::Visual* visual);
~XlibWindow (void);
void setVisibility (bool visible);
void processEvents (void);
DisplayBase& getDisplay (void) { return (DisplayBase&)m_display; }
::Window& getXID (void) { return m_window; }
void getDimensions (int* width, int* height) const;
void setDimensions (int width, int height);
protected:
XlibDisplay& m_display;
::Colormap m_colormap;
::Window m_window;
private:
XlibWindow (const XlibWindow&);
XlibWindow& operator= (const XlibWindow&);
};
} // x11
} // tcu
#endif // _TCUX11_HPP
| chadversary/deqp | framework/platform/X11/tcuX11.hpp | C++ | apache-2.0 | 3,554 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "data/constructs/column.h"
#include <string>
#include "data/constructs/inputvalidation.h"
namespace cclient {
namespace data {
void Column::setColFamily(const char *r, uint32_t size) {
columnFamily = std::string(r, size);
}
void Column::setColQualifier(const char *r, uint32_t size) {
columnQualifier = std::string(r, size);
}
void Column::setColVisibility(const char *r, uint32_t size) {
columnVisibility = std::string(r, size);
}
Column::~Column() {}
bool Column::operator<(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare < 0) return true;
return false;
}
bool Column::operator==(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare != 0) return false;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare != 0) return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare != 0)
return false;
else
return true;
}
uint64_t Column::write(cclient::data::streams::OutputStream *outStream) {
if (columnFamily.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnFamily.data(), columnFamily.size());
}
if (columnQualifier.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnQualifier.data(), columnQualifier.size());
}
if (columnVisibility.empty()) {
return outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
return outStream->writeBytes(columnVisibility.data(),
columnVisibility.size());
}
}
} // namespace data
} // namespace cclient
| phrocker/sharkbite | src/data/constructs/column.cpp | C++ | apache-2.0 | 3,199 |
package me.knox.zmz.mvp.model;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import java.util.List;
import javax.inject.Inject;
import me.knox.zmz.App;
import me.knox.zmz.entity.News;
import me.knox.zmz.mvp.contract.NewsListContract;
import me.knox.zmz.network.JsonResponse;
/**
* Created by KNOX.
*/
public class NewsListModel implements NewsListContract.Model {
@Inject public NewsListModel() {
// empty constructor for injection
}
@Override public Flowable<JsonResponse<List<News>>> getNewsList() {
return App.getInstance().getApi().getNews().observeOn(AndroidSchedulers.mainThread(), true);
}
}
| chowaikong/ZMZ | app/src/main/java/me/knox/zmz/mvp/model/NewsListModel.java | Java | apache-2.0 | 664 |
/*
* Copyright 2022 Imply Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ESLintUtils } from '@typescript-eslint/utils';
import { readonlyImplicitFields } from './readonly-implicit-fields';
const ruleTester = new ESLintUtils.RuleTester({
parser: '@typescript-eslint/parser',
});
ruleTester.run('readonly-implicit-fields', readonlyImplicitFields, {
valid: [
// Various valid cases inside of Immutable Classes
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
private readonly baz: number;
public readonly qux: () => void;
public getBaz = () => this.baz;
public changeBaz = (baz: number) => this;
public doStuff(): string { return 'stuff'; }
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
public declare readonly foo: string;
private declare readonly foo: string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
public declare readonly getFoo: () => string;
private declare readonly getFoo: () => string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly changeFoo: (foo: string) => MyClass;
public declare readonly changeFoo: (foo: string) => MyClass;
private declare readonly changeFoo: (foo: string) => MyClass;
}`,
// Invalid cases but not inside of BaseImmutable inheritors
`class MyClass extends NotImmutable {
declare foo: string;
}`,
`class MyClass extends NotImmutable {
public declare foo: string;
}`,
`class MyClass extends NotImmutable {
private declare foo: string;
}`,
],
invalid: [
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly getFoo: () => string;
}`,
},
// Weird spacing
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare foo : string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 4, column: 13 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare readonly foo : string;
}`,
},
],
});
| implydata/immutable-class | packages/eslint-plugin-immutable-class/src/rules/readonly-implicit-fields.spec.ts | TypeScript | apache-2.0 | 5,020 |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.toMap;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.annotation.OnSave;
import com.googlecode.objectify.annotation.Parent;
import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
import google.registry.model.annotations.InCrossTld;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.common.EntityGroupRoot;
import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.common.TimedTransitionProperty.TimedTransition;
import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Fee;
import google.registry.model.replay.DatastoreAndSqlEntity;
import google.registry.model.tld.label.PremiumList;
import google.registry.model.tld.label.ReservedList;
import google.registry.persistence.VKey;
import google.registry.persistence.converter.JodaMoneyType;
import google.registry.util.Idn;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PostLoad;
import javax.persistence.Transient;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
/** Persisted per-TLD configuration data. */
@ReportedOn
@Entity
@javax.persistence.Entity(name = "Tld")
@InCrossTld
public class Registry extends ImmutableObject
implements Buildable, DatastoreAndSqlEntity, UnsafeSerializable {
@Parent @Transient Key<EntityGroupRoot> parent = getCrossTldKey();
/**
* The canonical string representation of the TLD associated with this {@link Registry}, which is
* the standard ASCII for regular TLDs and punycoded ASCII for IDN TLDs.
*/
@Id
@javax.persistence.Id
@Column(name = "tld_name", nullable = false)
String tldStrId;
/**
* A duplicate of {@link #tldStrId}, to simplify BigQuery reporting since the id field becomes
* {@code __key__.name} rather than being exported as a named field.
*/
@Transient String tldStr;
/** Sets the Datastore specific field, tldStr, when the entity is loaded from Cloud SQL */
@PostLoad
void postLoad() {
tldStr = tldStrId;
}
/** The suffix that identifies roids as belonging to this specific tld, e.g. -HOW for .how. */
String roidSuffix;
/** Default values for all the relevant TLD parameters. */
public static final TldState DEFAULT_TLD_STATE = TldState.PREDELEGATION;
public static final boolean DEFAULT_ESCROW_ENABLED = false;
public static final boolean DEFAULT_DNS_PAUSED = false;
public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.standardDays(45);
public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.standardDays(30);
public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.standardDays(30);
public static final CurrencyUnit DEFAULT_CURRENCY = USD;
public static final Money DEFAULT_CREATE_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_EAP_BILLING_COST = Money.of(USD, 0);
public static final Money DEFAULT_RENEW_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_RESTORE_BILLING_COST = Money.of(USD, 100);
public static final Money DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST = Money.of(USD, 20);
public static final Money DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST = Money.of(USD, 0);
/** The type of TLD, which determines things like backups and escrow policy. */
public enum TldType {
/** A real, official TLD. */
REAL,
/** A test TLD, for the prober. */
TEST
}
/**
* The states a TLD can be in at any given point in time. The ordering below is the required
* sequence of states (ignoring {@link #PDT} which is a pseudo-state).
*/
public enum TldState {
/** The state of not yet being delegated to this registry in the root zone by IANA. */
PREDELEGATION,
/**
* The state in which only trademark holders can submit a "create" request. It is identical to
* {@link #GENERAL_AVAILABILITY} in all other respects.
*/
START_DATE_SUNRISE,
/**
* A state in which no domain operations are permitted. Generally used between sunrise and
* general availability. This state is special in that it has no ordering constraints and can
* appear after any phase.
*/
QUIET_PERIOD,
/**
* The steady state of a TLD in which all domain names are available via first-come,
* first-serve.
*/
GENERAL_AVAILABILITY,
/** A "fake" state for use in predelegation testing. Acts like {@link #GENERAL_AVAILABILITY}. */
PDT
}
/**
* A transition to a TLD state at a specific time, for use in a TimedTransitionProperty. Public
* because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class TldStateTransition extends TimedTransition<TldState> {
/** The TLD state. */
private TldState tldState;
@Override
public TldState getValue() {
return tldState;
}
@Override
protected void setValue(TldState tldState) {
this.tldState = tldState;
}
}
/**
* A transition to a given billing cost at a specific time, for use in a TimedTransitionProperty.
*
* <p>Public because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class BillingCostTransition extends TimedTransition<Money> {
/** The billing cost value. */
private Money billingCost;
@Override
public Money getValue() {
return billingCost;
}
@Override
protected void setValue(Money billingCost) {
this.billingCost = billingCost;
}
}
/** Returns the registry for a given TLD, throwing if none exists. */
public static Registry get(String tld) {
Registry registry = CACHE.getUnchecked(tld).orElse(null);
if (registry == null) {
throw new RegistryNotFoundException(tld);
}
return registry;
}
/** Returns the registry entities for the given TLD strings, throwing if any don't exist. */
static ImmutableSet<Registry> getAll(Set<String> tlds) {
try {
ImmutableMap<String, Optional<Registry>> registries = CACHE.getAll(tlds);
ImmutableSet<String> missingRegistries =
registries.entrySet().stream()
.filter(e -> !e.getValue().isPresent())
.map(Map.Entry::getKey)
.collect(toImmutableSet());
if (missingRegistries.isEmpty()) {
return registries.values().stream().map(Optional::get).collect(toImmutableSet());
} else {
throw new RegistryNotFoundException(missingRegistries);
}
} catch (ExecutionException e) {
throw new RuntimeException("Unexpected error retrieving TLDs " + tlds, e);
}
}
/**
* Invalidates the cache entry.
*
* <p>This is called automatically when the registry is saved. One should also call it when a
* registry is deleted.
*/
@OnSave
public void invalidateInCache() {
CACHE.invalidate(tldStr);
}
/** A cache that loads the {@link Registry} for a given tld. */
private static final LoadingCache<String, Optional<Registry>> CACHE =
CacheBuilder.newBuilder()
.expireAfterWrite(
java.time.Duration.ofMillis(getSingletonCacheRefreshDuration().getMillis()))
.build(
new CacheLoader<String, Optional<Registry>>() {
@Override
public Optional<Registry> load(final String tld) {
// Enter a transaction-less context briefly; we don't want to enroll every TLD in
// a transaction that might be wrapping this call.
return tm().doTransactionless(() -> tm().loadByKeyIfPresent(createVKey(tld)));
}
@Override
public Map<String, Optional<Registry>> loadAll(Iterable<? extends String> tlds) {
ImmutableMap<String, VKey<Registry>> keysMap =
toMap(ImmutableSet.copyOf(tlds), Registry::createVKey);
Map<VKey<? extends Registry>, Registry> entities =
tm().doTransactionless(() -> tm().loadByKeys(keysMap.values()));
return Maps.transformEntries(
keysMap, (k, v) -> Optional.ofNullable(entities.getOrDefault(v, null)));
}
});
public static VKey<Registry> createVKey(String tld) {
return VKey.create(Registry.class, tld, Key.create(getCrossTldKey(), Registry.class, tld));
}
public static VKey<Registry> createVKey(Key<Registry> key) {
return createVKey(key.getName());
}
/**
* The name of the pricing engine that this TLD uses.
*
* <p>This must be a valid key for the map of pricing engines injected by {@code @Inject
* Map<String, PricingEngine>}.
*
* <p>Note that it used to be the canonical class name, hence the name of this field, but this
* restriction has since been relaxed and it may now be any unique string.
*/
String pricingEngineClassName;
/**
* The set of name(s) of the {@code DnsWriter} implementations that this TLD uses.
*
* <p>There must be at least one entry in this set.
*
* <p>All entries of this list must be valid keys for the map of {@code DnsWriter}s injected by
* {@code @Inject Map<String, DnsWriter>}
*/
@Column(nullable = false)
Set<String> dnsWriters;
/**
* The number of locks we allow at once for {@link google.registry.dns.PublishDnsUpdatesAction}.
*
* <p>This should always be a positive integer- use 1 for TLD-wide locks. All {@link Registry}
* objects have this value default to 1.
*
* <p>WARNING: changing this parameter changes the lock name for subsequent DNS updates, and thus
* invalidates the locking scheme for enqueued DNS publish updates. If the {@link
* google.registry.dns.writer.DnsWriter} you use is not parallel-write tolerant, you must follow
* this procedure to change this value:
*
* <ol>
* <li>Pause the DNS queue via {@link google.registry.tools.UpdateTldCommand}
* <li>Change this number
* <li>Let the Registry caches expire (currently 5 minutes) and drain the DNS publish queue
* <li>Unpause the DNS queue
* </ol>
*
* <p>Failure to do so can result in parallel writes to the {@link
* google.registry.dns.writer.DnsWriter}, which may be dangerous depending on your implementation.
*/
@Column(nullable = false)
int numDnsPublishLocks;
/** Updates an unset numDnsPublishLocks (0) to the standard default of 1. */
void setDefaultNumDnsPublishLocks() {
if (numDnsPublishLocks == 0) {
numDnsPublishLocks = 1;
}
}
/**
* The unicode-aware representation of the TLD associated with this {@link Registry}.
*
* <p>This will be equal to {@link #tldStr} for ASCII TLDs, but will be non-ASCII for IDN TLDs. We
* store this in a field so that it will be retained upon import into BigQuery.
*/
@Column(nullable = false)
String tldUnicode;
/**
* Id of the folder in drive used to public (export) information for this TLD.
*
* <p>This is optional; if not configured, then information won't be exported for this TLD.
*/
@Nullable String driveFolderId;
/** The type of the TLD, whether it's real or for testing. */
@Column(nullable = false)
@Enumerated(EnumType.STRING)
TldType tldType = TldType.REAL;
/**
* Whether to enable invoicing for this TLD.
*
* <p>Note that this boolean is the sole determiner on whether invoices should be generated for a
* TLD. This applies to {@link TldType#TEST} TLDs as well.
*/
@Column(nullable = false)
boolean invoicingEnabled = false;
/**
* A property that transitions to different TldStates at different times. Stored as a list of
* TldStateTransition embedded objects using the @Mapify annotation.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<TldState, TldStateTransition> tldStateTransitions =
TimedTransitionProperty.forMapify(DEFAULT_TLD_STATE, TldStateTransition.class);
/** An automatically managed creation timestamp. */
@Column(nullable = false)
CreateAutoTimestamp creationTime = CreateAutoTimestamp.create(null);
/** The set of reserved list names that are applicable to this registry. */
@Column(name = "reserved_list_names")
Set<String> reservedListNames;
/**
* Retrieves an ImmutableSet of all ReservedLists associated with this TLD.
*
* <p>This set contains only the names of the list and not a reference to the lists. Updates to a
* reserved list in Cloud SQL are saved as a new ReservedList entity. When using the ReservedList
* for a registry, the database should be queried for the entity with this name that has the
* largest revision ID.
*/
public ImmutableSet<String> getReservedListNames() {
return nullToEmptyImmutableCopy(reservedListNames);
}
/**
* The name of the {@link PremiumList} for this TLD, if there is one.
*
* <p>This is only the name of the list and not a reference to the list. Updates to the premium
* list in Cloud SQL are saved as a new PremiumList entity. When using the PremiumList for a
* registry, the database should be queried for the entity with this name that has the largest
* revision ID.
*/
@Column(name = "premium_list_name", nullable = true)
String premiumListName;
/** Should RDE upload a nightly escrow deposit for this TLD? */
@Column(nullable = false)
boolean escrowEnabled = DEFAULT_ESCROW_ENABLED;
/** Whether the pull queue that writes to authoritative DNS is paused for this TLD. */
@Column(nullable = false)
boolean dnsPaused = DEFAULT_DNS_PAUSED;
/**
* The length of the add grace period for this TLD.
*
* <p>Domain deletes are free and effective immediately so long as they take place within this
* amount of time following creation.
*/
@Column(nullable = false)
Duration addGracePeriodLength = DEFAULT_ADD_GRACE_PERIOD;
/** The length of the anchor tenant add grace period for this TLD. */
@Column(nullable = false)
Duration anchorTenantAddGracePeriodLength = DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD;
/** The length of the auto renew grace period for this TLD. */
@Column(nullable = false)
Duration autoRenewGracePeriodLength = DEFAULT_AUTO_RENEW_GRACE_PERIOD;
/** The length of the redemption grace period for this TLD. */
@Column(nullable = false)
Duration redemptionGracePeriodLength = DEFAULT_REDEMPTION_GRACE_PERIOD;
/** The length of the renew grace period for this TLD. */
@Column(nullable = false)
Duration renewGracePeriodLength = DEFAULT_RENEW_GRACE_PERIOD;
/** The length of the transfer grace period for this TLD. */
@Column(nullable = false)
Duration transferGracePeriodLength = DEFAULT_TRANSFER_GRACE_PERIOD;
/** The length of time before a transfer is automatically approved for this TLD. */
@Column(nullable = false)
Duration automaticTransferLength = DEFAULT_AUTOMATIC_TRANSFER_LENGTH;
/** The length of time a domain spends in the non-redeemable pending delete phase for this TLD. */
@Column(nullable = false)
Duration pendingDeleteLength = DEFAULT_PENDING_DELETE_LENGTH;
/** The currency unit for all costs associated with this TLD. */
@Column(nullable = false)
CurrencyUnit currency = DEFAULT_CURRENCY;
/** The per-year billing cost for registering a new domain name. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "create_billing_cost_amount"),
@Column(name = "create_billing_cost_currency")
})
Money createBillingCost = DEFAULT_CREATE_BILLING_COST;
/** The one-time billing cost for restoring a domain name from the redemption grace period. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "restore_billing_cost_amount"),
@Column(name = "restore_billing_cost_currency")
})
Money restoreBillingCost = DEFAULT_RESTORE_BILLING_COST;
/** The one-time billing cost for changing the server status (i.e. lock). */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "server_status_change_billing_cost_amount"),
@Column(name = "server_status_change_billing_cost_currency")
})
Money serverStatusChangeBillingCost = DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST;
/** The one-time billing cost for a registry lock/unlock action initiated by a registrar. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "registry_lock_or_unlock_cost_amount"),
@Column(name = "registry_lock_or_unlock_cost_currency")
})
Money registryLockOrUnlockBillingCost = DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST;
/**
* A property that transitions to different renew billing costs at different times. Stored as a
* list of BillingCostTransition embedded objects using the @Mapify annotation.
*
* <p>A given value of this property represents the per-year billing cost for renewing a domain
* name. This cost is also used to compute costs for transfers, since each transfer includes a
* renewal to ensure transfers have a cost.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> renewBillingCostTransitions =
TimedTransitionProperty.forMapify(DEFAULT_RENEW_BILLING_COST, BillingCostTransition.class);
/** A property that tracks the EAP fee schedule (if any) for the TLD. */
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> eapFeeSchedule =
TimedTransitionProperty.forMapify(DEFAULT_EAP_BILLING_COST, BillingCostTransition.class);
/** Marksdb LORDN service username (password is stored in Keyring) */
String lordnUsername;
/** The end of the claims period (at or after this time, claims no longer applies). */
@Column(nullable = false)
DateTime claimsPeriodEnd = END_OF_TIME;
/** An allow list of clients allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedRegistrantContactIds;
/** An allow list of hosts allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedFullyQualifiedHostNames;
public String getTldStr() {
return tldStr;
}
public String getRoidSuffix() {
return roidSuffix;
}
/** Retrieve the actual domain name representing the TLD for which this registry operates. */
public InternetDomainName getTld() {
return InternetDomainName.from(tldStr);
}
/** Retrieve the TLD type (real or test). */
public TldType getTldType() {
return tldType;
}
/**
* Retrieve the TLD state at the given time. Defaults to {@link TldState#PREDELEGATION}.
*
* <p>Note that {@link TldState#PDT} TLDs pretend to be in {@link TldState#GENERAL_AVAILABILITY}.
*/
public TldState getTldState(DateTime now) {
TldState state = tldStateTransitions.getValueAtTime(now);
return TldState.PDT.equals(state) ? TldState.GENERAL_AVAILABILITY : state;
}
/** Retrieve whether this TLD is in predelegation testing. */
public boolean isPdt(DateTime now) {
return TldState.PDT.equals(tldStateTransitions.getValueAtTime(now));
}
public DateTime getCreationTime() {
return creationTime.getTimestamp();
}
public boolean getEscrowEnabled() {
return escrowEnabled;
}
public boolean getDnsPaused() {
return dnsPaused;
}
public String getDriveFolderId() {
return driveFolderId;
}
public Duration getAddGracePeriodLength() {
return addGracePeriodLength;
}
public Duration getAutoRenewGracePeriodLength() {
return autoRenewGracePeriodLength;
}
public Duration getRedemptionGracePeriodLength() {
return redemptionGracePeriodLength;
}
public Duration getRenewGracePeriodLength() {
return renewGracePeriodLength;
}
public Duration getTransferGracePeriodLength() {
return transferGracePeriodLength;
}
public Duration getAutomaticTransferLength() {
return automaticTransferLength;
}
public Duration getPendingDeleteLength() {
return pendingDeleteLength;
}
public Duration getAnchorTenantAddGracePeriodLength() {
return anchorTenantAddGracePeriodLength;
}
public Optional<String> getPremiumListName() {
return Optional.ofNullable(premiumListName);
}
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Use <code>PricingEngineProxy.getDomainCreateCost</code> instead of this to find the cost for a
* domain create.
*/
@VisibleForTesting
public Money getStandardCreateCost() {
return createBillingCost;
}
/**
* Returns the add-on cost of a domain restore (the flat registry-wide fee charged in addition to
* one year of renewal for that name).
*/
public Money getStandardRestoreCost() {
return restoreBillingCost;
}
/**
* Use <code>PricingEngineProxy.getDomainRenewCost</code> instead of this to find the cost for a
* domain renewal, and all derived costs (i.e. autorenews, transfers, and the per-domain part of a
* restore cost).
*/
public Money getStandardRenewCost(DateTime now) {
return renewBillingCostTransitions.getValueAtTime(now);
}
/** Returns the cost of a server status change (i.e. lock). */
public Money getServerStatusChangeCost() {
return serverStatusChangeBillingCost;
}
/** Returns the cost of a registry lock/unlock. */
public Money getRegistryLockOrUnlockBillingCost() {
return registryLockOrUnlockBillingCost;
}
public ImmutableSortedMap<DateTime, TldState> getTldStateTransitions() {
return tldStateTransitions.toValueMap();
}
public ImmutableSortedMap<DateTime, Money> getRenewBillingCostTransitions() {
return renewBillingCostTransitions.toValueMap();
}
/** Returns the EAP fee for the registry at the given time. */
public Fee getEapFeeFor(DateTime now) {
ImmutableSortedMap<DateTime, Money> valueMap = getEapFeeScheduleAsMap();
DateTime periodStart = valueMap.floorKey(now);
DateTime periodEnd = valueMap.ceilingKey(now);
// NOTE: assuming END_OF_TIME would never be reached...
Range<DateTime> validPeriod =
Range.closedOpen(
periodStart != null ? periodStart : START_OF_TIME,
periodEnd != null ? periodEnd : END_OF_TIME);
return Fee.create(
eapFeeSchedule.getValueAtTime(now).getAmount(),
FeeType.EAP,
// An EAP fee does not count as premium -- it's a separate one-time fee, independent of
// which the domain is separately considered standard vs premium depending on renewal price.
false,
validPeriod,
validPeriod.upperEndpoint());
}
@VisibleForTesting
public ImmutableSortedMap<DateTime, Money> getEapFeeScheduleAsMap() {
return eapFeeSchedule.toValueMap();
}
public String getLordnUsername() {
return lordnUsername;
}
public DateTime getClaimsPeriodEnd() {
return claimsPeriodEnd;
}
public String getPremiumPricingEngineClassName() {
return pricingEngineClassName;
}
public ImmutableSet<String> getDnsWriters() {
return ImmutableSet.copyOf(dnsWriters);
}
/** Returns the number of simultaneous DNS publish operations we allow at once. */
public int getNumDnsPublishLocks() {
return numDnsPublishLocks;
}
public ImmutableSet<String> getAllowedRegistrantContactIds() {
return nullToEmptyImmutableCopy(allowedRegistrantContactIds);
}
public ImmutableSet<String> getAllowedFullyQualifiedHostNames() {
return nullToEmptyImmutableCopy(allowedFullyQualifiedHostNames);
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link Registry} objects, since they are immutable. */
public static class Builder extends Buildable.Builder<Registry> {
public Builder() {}
private Builder(Registry instance) {
super(instance);
}
public Builder setTldType(TldType tldType) {
getInstance().tldType = tldType;
return this;
}
public Builder setInvoicingEnabled(boolean invoicingEnabled) {
getInstance().invoicingEnabled = invoicingEnabled;
return this;
}
/** Sets the TLD state to transition to the specified states at the specified times. */
public Builder setTldStateTransitions(ImmutableSortedMap<DateTime, TldState> tldStatesMap) {
checkNotNull(tldStatesMap, "TLD states map cannot be null");
// Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since
// that phase is allowed to appear anywhere.
checkArgument(
Ordering.natural()
.isStrictlyOrdered(
Iterables.filter(tldStatesMap.values(), not(equalTo(TldState.QUIET_PERIOD)))),
"The TLD states are chronologically out of order");
getInstance().tldStateTransitions =
TimedTransitionProperty.fromValueMap(tldStatesMap, TldStateTransition.class);
return this;
}
public Builder setTldStr(String tldStr) {
checkArgument(tldStr != null, "TLD must not be null");
getInstance().tldStr = tldStr;
return this;
}
public Builder setEscrowEnabled(boolean enabled) {
getInstance().escrowEnabled = enabled;
return this;
}
public Builder setDnsPaused(boolean paused) {
getInstance().dnsPaused = paused;
return this;
}
public Builder setDriveFolderId(String driveFolderId) {
getInstance().driveFolderId = driveFolderId;
return this;
}
public Builder setPremiumPricingEngine(String pricingEngineClass) {
getInstance().pricingEngineClassName = checkArgumentNotNull(pricingEngineClass);
return this;
}
public Builder setDnsWriters(ImmutableSet<String> dnsWriters) {
getInstance().dnsWriters = dnsWriters;
return this;
}
public Builder setNumDnsPublishLocks(int numDnsPublishLocks) {
checkArgument(
numDnsPublishLocks > 0,
"numDnsPublishLocks must be positive when set explicitly (use 1 for TLD-wide locks)");
getInstance().numDnsPublishLocks = numDnsPublishLocks;
return this;
}
public Builder setAddGracePeriodLength(Duration addGracePeriodLength) {
checkArgument(
addGracePeriodLength.isLongerThan(Duration.ZERO),
"addGracePeriodLength must be non-zero");
getInstance().addGracePeriodLength = addGracePeriodLength;
return this;
}
/** Warning! Changing this will affect the billing time of autorenew events in the past. */
public Builder setAutoRenewGracePeriodLength(Duration autoRenewGracePeriodLength) {
checkArgument(
autoRenewGracePeriodLength.isLongerThan(Duration.ZERO),
"autoRenewGracePeriodLength must be non-zero");
getInstance().autoRenewGracePeriodLength = autoRenewGracePeriodLength;
return this;
}
public Builder setRedemptionGracePeriodLength(Duration redemptionGracePeriodLength) {
checkArgument(
redemptionGracePeriodLength.isLongerThan(Duration.ZERO),
"redemptionGracePeriodLength must be non-zero");
getInstance().redemptionGracePeriodLength = redemptionGracePeriodLength;
return this;
}
public Builder setRenewGracePeriodLength(Duration renewGracePeriodLength) {
checkArgument(
renewGracePeriodLength.isLongerThan(Duration.ZERO),
"renewGracePeriodLength must be non-zero");
getInstance().renewGracePeriodLength = renewGracePeriodLength;
return this;
}
public Builder setTransferGracePeriodLength(Duration transferGracePeriodLength) {
checkArgument(
transferGracePeriodLength.isLongerThan(Duration.ZERO),
"transferGracePeriodLength must be non-zero");
getInstance().transferGracePeriodLength = transferGracePeriodLength;
return this;
}
public Builder setAutomaticTransferLength(Duration automaticTransferLength) {
checkArgument(
automaticTransferLength.isLongerThan(Duration.ZERO),
"automaticTransferLength must be non-zero");
getInstance().automaticTransferLength = automaticTransferLength;
return this;
}
public Builder setPendingDeleteLength(Duration pendingDeleteLength) {
checkArgument(
pendingDeleteLength.isLongerThan(Duration.ZERO), "pendingDeleteLength must be non-zero");
getInstance().pendingDeleteLength = pendingDeleteLength;
return this;
}
public Builder setCurrency(CurrencyUnit currency) {
checkArgument(currency != null, "currency must be non-null");
getInstance().currency = currency;
return this;
}
public Builder setCreateBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "createBillingCost cannot be negative");
getInstance().createBillingCost = amount;
return this;
}
public Builder setReservedListsByName(Set<String> reservedListNames) {
checkArgument(reservedListNames != null, "reservedListNames must not be null");
ImmutableSet.Builder<ReservedList> builder = new ImmutableSet.Builder<>();
for (String reservedListName : reservedListNames) {
// Check for existence of the reserved list and throw an exception if it doesn't exist.
Optional<ReservedList> reservedList = ReservedList.get(reservedListName);
checkArgument(
reservedList.isPresent(),
"Could not find reserved list %s to add to the tld",
reservedListName);
builder.add(reservedList.get());
}
return setReservedLists(builder.build());
}
public Builder setReservedLists(ReservedList... reservedLists) {
return setReservedLists(ImmutableSet.copyOf(reservedLists));
}
public Builder setReservedLists(Set<ReservedList> reservedLists) {
checkArgumentNotNull(reservedLists, "reservedLists must not be null");
ImmutableSet.Builder<String> nameBuilder = new ImmutableSet.Builder<>();
for (ReservedList reservedList : reservedLists) {
nameBuilder.add(reservedList.getName());
}
getInstance().reservedListNames = nameBuilder.build();
return this;
}
public Builder setPremiumList(@Nullable PremiumList premiumList) {
getInstance().premiumListName = (premiumList == null) ? null : premiumList.getName();
return this;
}
public Builder setRestoreBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "restoreBillingCost cannot be negative");
getInstance().restoreBillingCost = amount;
return this;
}
/**
* Sets the renew billing cost to transition to the specified values at the specified times.
*
* <p>Renew billing costs transitions should only be added at least 5 days (the length of an
* automatic transfer) in advance, to avoid discrepancies between the cost stored with the
* billing event (created when the transfer is requested) and the cost at the time when the
* transfer actually occurs (5 days later).
*/
public Builder setRenewBillingCostTransitions(
ImmutableSortedMap<DateTime, Money> renewCostsMap) {
checkArgumentNotNull(renewCostsMap, "Renew billing costs map cannot be null");
checkArgument(
renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero),
"Renew billing cost cannot be negative");
getInstance().renewBillingCostTransitions =
TimedTransitionProperty.fromValueMap(renewCostsMap, BillingCostTransition.class);
return this;
}
/** Sets the EAP fee schedule for the TLD. */
public Builder setEapFeeSchedule(ImmutableSortedMap<DateTime, Money> eapFeeSchedule) {
checkArgumentNotNull(eapFeeSchedule, "EAP schedule map cannot be null");
checkArgument(
eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero),
"EAP fee cannot be negative");
getInstance().eapFeeSchedule =
TimedTransitionProperty.fromValueMap(eapFeeSchedule, BillingCostTransition.class);
return this;
}
private static final Pattern ROID_SUFFIX_PATTERN = Pattern.compile("^[A-Z0-9_]{1,8}$");
public Builder setRoidSuffix(String roidSuffix) {
checkArgument(
ROID_SUFFIX_PATTERN.matcher(roidSuffix).matches(),
"ROID suffix must be in format %s",
ROID_SUFFIX_PATTERN.pattern());
getInstance().roidSuffix = roidSuffix;
return this;
}
public Builder setServerStatusChangeBillingCost(Money amount) {
checkArgument(
amount.isPositiveOrZero(), "Server status change billing cost cannot be negative");
getInstance().serverStatusChangeBillingCost = amount;
return this;
}
public Builder setRegistryLockOrUnlockBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "Registry lock/unlock cost cannot be negative");
getInstance().registryLockOrUnlockBillingCost = amount;
return this;
}
public Builder setLordnUsername(String username) {
getInstance().lordnUsername = username;
return this;
}
public Builder setClaimsPeriodEnd(DateTime claimsPeriodEnd) {
getInstance().claimsPeriodEnd = checkArgumentNotNull(claimsPeriodEnd);
return this;
}
public Builder setAllowedRegistrantContactIds(
ImmutableSet<String> allowedRegistrantContactIds) {
getInstance().allowedRegistrantContactIds = allowedRegistrantContactIds;
return this;
}
public Builder setAllowedFullyQualifiedHostNames(
ImmutableSet<String> allowedFullyQualifiedHostNames) {
getInstance().allowedFullyQualifiedHostNames = allowedFullyQualifiedHostNames;
return this;
}
@Override
public Registry build() {
final Registry instance = getInstance();
// Pick up the name of the associated TLD from the instance object.
String tldName = instance.tldStr;
checkArgument(tldName != null, "No registry TLD specified");
// Check for canonical form by converting to an InternetDomainName and then back.
checkArgument(
InternetDomainName.isValid(tldName)
&& tldName.equals(InternetDomainName.from(tldName).toString()),
"Cannot create registry for TLD that is not a valid, canonical domain name");
// Check the validity of all TimedTransitionProperties to ensure that they have values for
// START_OF_TIME. The setters above have already checked this for new values, but also check
// here to catch cases where we loaded an invalid TimedTransitionProperty from Datastore and
// cloned it into a new builder, to block re-building a Registry in an invalid state.
instance.tldStateTransitions.checkValidity();
instance.renewBillingCostTransitions.checkValidity();
instance.eapFeeSchedule.checkValidity();
// All costs must be in the expected currency.
// TODO(b/21854155): When we move PremiumList into Datastore, verify its currency too.
checkArgument(
instance.getStandardCreateCost().getCurrencyUnit().equals(instance.currency),
"Create cost must be in the registry's currency");
checkArgument(
instance.getStandardRestoreCost().getCurrencyUnit().equals(instance.currency),
"Restore cost must be in the registry's currency");
checkArgument(
instance.getServerStatusChangeCost().getCurrencyUnit().equals(instance.currency),
"Server status change cost must be in the registry's currency");
checkArgument(
instance.getRegistryLockOrUnlockBillingCost().getCurrencyUnit().equals(instance.currency),
"Registry lock/unlock cost must be in the registry's currency");
Predicate<Money> currencyCheck =
(Money money) -> money.getCurrencyUnit().equals(instance.currency);
checkArgument(
instance.getRenewBillingCostTransitions().values().stream().allMatch(currencyCheck),
"Renew cost must be in the registry's currency");
checkArgument(
instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck),
"All EAP fees must be in the registry's currency");
checkArgumentNotNull(
instance.pricingEngineClassName, "All registries must have a configured pricing engine");
checkArgument(
instance.dnsWriters != null && !instance.dnsWriters.isEmpty(),
"At least one DNS writer must be specified."
+ " VoidDnsWriter can be used if DNS writing isn't desired");
// If not set explicitly, numDnsPublishLocks defaults to 1.
instance.setDefaultNumDnsPublishLocks();
checkArgument(
instance.numDnsPublishLocks > 0,
"Number of DNS publish locks must be positive. Use 1 for TLD-wide locks.");
instance.tldStrId = tldName;
instance.tldUnicode = Idn.toUnicode(tldName);
return super.build();
}
}
/** Exception to throw when no Registry entity is found for given TLD string(s). */
public static class RegistryNotFoundException extends RuntimeException {
RegistryNotFoundException(ImmutableSet<String> tlds) {
super("No registry object(s) found for " + Joiner.on(", ").join(tlds));
}
RegistryNotFoundException(String tld) {
this(ImmutableSet.of(tld));
}
}
}
| google/nomulus | core/src/main/java/google/registry/model/tld/Registry.java | Java | apache-2.0 | 40,835 |
import java.util.Scanner;
/**
* @author Oleg Cherednik
* @since 27.10.2017
*/
public class Solution {
static int[] leftRotation(int[] a, int d) {
for (int i = 0, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
d %= a.length;
if (d > 0) {
d = a.length - d;
for (int i = 0, j = d - 1; i < j; i++, j--)
swap(a, i, j);
for (int i = d, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
}
return a;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int[] result = leftRotation(a, d);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println("");
in.close();
}
}
| oleg-cherednik/hackerrank | Data Structures/Arrays/Left Rotation/Solution.java | Java | apache-2.0 | 1,184 |
package com.pmis.manage.dao;
import org.springframework.stereotype.Component;
import com.pmis.common.dao.CommonDao;
@Component
public class UserInfoDao extends CommonDao{
}
| twosunnus/zhcy | src/com/pmis/manage/dao/UserInfoDao.java | Java | apache-2.0 | 193 |
/**
* Licensed to Odiago, Inc. under one or more contributor license
* agreements. See the NOTICE.txt file distributed with this work for
* additional information regarding copyright ownership. Odiago, Inc.
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.odiago.flumebase.lang;
import java.util.Collections;
import java.util.List;
/**
* Abstract base class that defines a callable function. Subclasses
* of this exist for scalar, aggregate, and table functions.
*/
public abstract class Function {
/**
* @return the Type of the object returned by the function.
*/
public abstract Type getReturnType();
/**
* @return an ordered list containing the types expected for all mandatory arguments.
*/
public abstract List<Type> getArgumentTypes();
/**
* @return an ordered list containing types expected for variable argument lists.
* If a function takes a variable-length argument list, the varargs must be arranged
* in groups matching the size of the list returned by this method. e.g., to accept
* an arbitrary number of strings, this should return a singleton list of type STRING.
* If pairs of strings and ints are required, this should return a list [STRING, INT].
*/
public List<Type> getVarArgTypes() {
return Collections.emptyList();
}
/**
* Determines whether arguments are promoted to their specified types by
* the runtime. If this returns true, actual arguments are promoted to
* new values that match the types specified in getArgumentTypes().
* If false, the expressions are simply type-checked to ensure that there
* is a valid promotion, but are passed in as-is. The default value of
* this method is true.
*/
public boolean autoPromoteArguments() {
return true;
}
}
| flumebase/flumebase | src/main/java/com/odiago/flumebase/lang/Function.java | Java | apache-2.0 | 2,315 |
/**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
/**
* Turns an onSuccess into an onComplete, onError and onComplete is relayed as is.
*
* @param <T> the value type
*/
public final class MaybeIgnoreElement<T> extends AbstractMaybeWithUpstream<T, T> {
public MaybeIgnoreElement(MaybeSource<T> source) {
super(source);
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
source.subscribe(new IgnoreMaybeObserver<T>(observer));
}
static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> actual;
Disposable d;
IgnoreMaybeObserver(MaybeObserver<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public boolean isDisposed() {
return d.isDisposed();
}
@Override
public void dispose() {
d.dispose();
d = DisposableHelper.DISPOSED;
}
}
}
| benjchristensen/RxJava | src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java | Java | apache-2.0 | 2,368 |
package com.intellij.util.xml.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NullableFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomNameStrategy;
import com.intellij.util.xml.EvaluatedXmlName;
import com.intellij.util.xml.stubs.ElementStub;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author peter
*/
public class DomRootInvocationHandler extends DomInvocationHandler<AbstractDomChildDescriptionImpl, ElementStub> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomRootInvocationHandler");
private final DomFileElementImpl<?> myParent;
public DomRootInvocationHandler(final Class aClass,
final RootDomParentStrategy strategy,
@Nonnull final DomFileElementImpl fileElement,
@Nonnull final EvaluatedXmlName tagName,
@Nullable ElementStub stub
) {
super(aClass, strategy, tagName, new AbstractDomChildDescriptionImpl(aClass) {
@Nonnull
public List<? extends DomElement> getValues(@Nonnull final DomElement parent) {
throw new UnsupportedOperationException();
}
public int compareTo(final AbstractDomChildDescriptionImpl o) {
throw new UnsupportedOperationException();
}
}, fileElement.getManager(), true, stub);
myParent = fileElement;
}
public void undefineInternal() {
try {
final XmlTag tag = getXmlTag();
if (tag != null) {
deleteTag(tag);
detach();
fireUndefinedEvent();
}
}
catch (Exception e) {
LOG.error(e);
}
}
public boolean equals(final Object obj) {
if (!(obj instanceof DomRootInvocationHandler)) return false;
final DomRootInvocationHandler handler = (DomRootInvocationHandler)obj;
return myParent.equals(handler.myParent);
}
public int hashCode() {
return myParent.hashCode();
}
@Nonnull
public String getXmlElementNamespace() {
return getXmlName().getNamespace(getFile(), getFile());
}
@Override
protected String checkValidity() {
final XmlTag tag = (XmlTag)getXmlElement();
if (tag != null && !tag.isValid()) {
return "invalid root tag";
}
final String s = myParent.checkValidity();
if (s != null) {
return "root: " + s;
}
return null;
}
@Nonnull
public DomFileElementImpl getParent() {
return myParent;
}
public DomElement createPathStableCopy() {
final DomFileElement stableCopy = myParent.createStableCopy();
return getManager().createStableValue(new NullableFactory<DomElement>() {
public DomElement create() {
return stableCopy.isValid() ? stableCopy.getRootElement() : null;
}
});
}
protected XmlTag setEmptyXmlTag() {
final XmlTag[] result = new XmlTag[]{null};
getManager().runChange(new Runnable() {
public void run() {
try {
final String namespace = getXmlElementNamespace();
@NonNls final String nsDecl = StringUtil.isEmpty(namespace) ? "" : " xmlns=\"" + namespace + "\"";
final XmlFile xmlFile = getFile();
final XmlTag tag = XmlElementFactory.getInstance(xmlFile.getProject()).createTagFromText("<" + getXmlElementName() + nsDecl + "/>");
result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
return result[0];
}
@Nonnull
public final DomNameStrategy getNameStrategy() {
final Class<?> rawType = getRawType();
final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute());
if (strategy != null) {
return strategy;
}
return DomNameStrategy.HYPHEN_STRATEGY;
}
}
| consulo/consulo-xml | xml-dom-impl/src/main/java/com/intellij/util/xml/impl/DomRootInvocationHandler.java | Java | apache-2.0 | 4,330 |
package org.consumersunion.stories.common.client.util;
public class CachedObjectKeys {
public static final String OPENED_CONTENT = "openedContent";
public static final String OPENED_STORY = "openedStory";
public static final String OPENED_COLLECTION = "openedCollection";
}
| stori-es/stori_es | dashboard/src/main/java/org/consumersunion/stories/common/client/util/CachedObjectKeys.java | Java | apache-2.0 | 287 |
package dkalymbaev.triangle;
class Triangle {
/**
* This class defines points a b and c as peacks of triangle.
*/
public Point a;
public Point b;
public Point c;
/**
* Creating of a new objects.
* @param a is the length of the first side.
* @param b is the length of the second side.
* @param c is the length of the third side.
*/
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double ab = a.distanceTo(b);
double bc = b.distanceTo(c);
double ac = a.distanceTo(c);
double halfperim = ((ab + bc + ac) / 2);
double area = Math.sqrt(halfperim * (halfperim - ab) * (halfperim - bc) * (halfperim - ac));
if (ab > 0 && bc > 0 && ac > 0) {
return area;
} else {
return 0;
}
}
} | Damir2805/java-a-to-z | Chapter_001/src/main/java/dkalymbaev/triangle/Triangle.java | Java | apache-2.0 | 783 |
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2019] EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ensembl.healthcheck.util;
import java.util.HashMap;
import java.util.Map;
/**
* A default implementation of the {@link MapRowMapper} intended as an
* extension point to help when creating these call back objects. This version
* will return a HashMap of the given generic types.
*
* @author ayates
* @author dstaines
*/
public abstract class AbstractMapRowMapper<K, T> implements MapRowMapper<K, T>{
public Map<K, T> getMap() {
return new HashMap<K,T>();
}
}
| Ensembl/ensj-healthcheck | src/org/ensembl/healthcheck/util/AbstractMapRowMapper.java | Java | apache-2.0 | 1,222 |
/**
* Created by plter on 6/13/16.
*/
(function () {
var files = ["hello.js", "app.js"];
files.forEach(function (file) {
var scriptTag = document.createElement("script");
scriptTag.async = false;
scriptTag.src = file;
document.body.appendChild(scriptTag);
});
}()); | plter/HTML5Course20160612 | 20160613/LoadScript/loader.js | JavaScript | apache-2.0 | 315 |
package com.linbo.algs.examples.queues;
import java.util.Iterator;
import com.linbo.algs.util.StdRandom;
/**
* Created by @linbojin on 13/1/17.
* Ref: http://coursera.cs.princeton.edu/algs4/assignments/queues.html
* RandomizedQueue: a double-ended queue or deque (pronounced "deck") is a
* generalization of a stack and a queue that supports adding and removing
* items from either the front or the back of the data structure.
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
// Memory: 16 + 8 + 4 + 4 + 4 + 4 + 24 + N * 4 * 2
// = 64 + 8N
private Item[] q; // queue elements
private int size; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot
// construct an empty randomized queue
public RandomizedQueue() {
q = (Item[]) new Object[2];
size = 0;
first = 0;
last = 0;
}
// is the queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the queue
public int size() {
return size;
}
// resize the underlying array
private void resize(int capacity) {
assert capacity >= size;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = size;
}
// add the item
public void enqueue(Item item) {
if (item == null) {
throw new java.lang.NullPointerException("Input item can not be null!");
}
// double size of array if necessary and recopy to front of array
if (size == q.length) resize(2 * q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
int i = index % q.length;
Item item = q[i];
last = (last + q.length - 1) % q.length;
if (i != last) {
q[i] = q[last];
}
q[last] = null;
size--;
// shrink size of array if necessary
if (size > 0 && size == q.length / 4) resize(q.length / 2);
return item;
}
// return (but do not remove) a random item
public Item sample() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
return q[index % q.length];
}
// an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
private int[] inxArr;
public ArrayIterator() {
inxArr = StdRandom.permutation(size);
}
public boolean hasNext() {
return i < size;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new java.util.NoSuchElementException();
Item item = q[(inxArr[i] + first) % q.length];
i++;
return item;
}
}
// unit testing (optional)
public static void main(String[] args) {
RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
System.out.println(rq.isEmpty());
rq.enqueue(1);
rq.enqueue(2);
rq.enqueue(3);
rq.enqueue(4);
rq.enqueue(5);
for (int i : rq) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("\n*******");
System.out.println(rq.sample());
System.out.println(rq.size()); // 5
System.out.println("*******");
System.out.println(rq.isEmpty());
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.sample());
System.out.println(rq.size()); // 3
System.out.println("*******");
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 1
System.out.println("*******");
System.out.println(rq.sample());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 0
System.out.println("*******");
RandomizedQueue<Integer> rqOne = new RandomizedQueue<Integer>();
System.out.println(rq.size());
rq.enqueue(4);
System.out.println(rq.size());
rq.enqueue(5);
System.out.println(rq.dequeue());
}
}
| linbojin/algorithms | java/src/main/java/com/linbo/algs/examples/queues/RandomizedQueue.java | Java | apache-2.0 | 4,619 |
/*
Copyright 2011 LinkedIn Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.linkedin.sample;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(y,last-name)";
private static String API_KEY = "77mahxt83mbma8";
private static String API_SECRET = "vpSWVa01dWq4dFfO";
public static void main(String[] args) {
/*
we need a OAuthService to handle authentication and the subsequent calls.
Since we are going to use the REST APIs we need to generate a request token as the first step in the call.
Once we get an access toke we can continue to use that until the API key changes or auth is revoked.
Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to
disk and then reuse it.
When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own
credentials and if there is a service.dat file in the code please delete it.
*/
//The Access Token is used in all Data calls to the APIs - it basically says our application has been given access
//to the approved information in LinkedIn
//Token accessToken = null;
//Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls.
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
/*************************************
* This first piece of code handles all the pieces needed to be granted access to make a data call
*/
Scanner in = new Scanner(System.in);
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
/*try{
File file = new File("service.txt");
if(file.exists()){
//if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
AuthHandler authHandler = (AuthHandler) inputStream.readObject();
accessToken = authHandler.getAccessToken();
} else {
System.out.println("There is no stored Access token we need to make one");
//In the constructor the AuthHandler goes through the chain of calls to create an Access Token
AuthHandler authHandler = new AuthHandler(service);
System.out.println("test");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.txt"));
outputStream.writeObject( authHandler);
outputStream.close();
accessToken = authHandler.getAccessToken();
}
}catch (Exception e){
System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage());
}
*//*
* We are all done getting access - time to get busy getting data
*************************************//*
*//**************************
*
* Querying the LinkedIn API
*
**************************//*
System.out.println();
System.out.println("********A basic user profile call********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/profile-api
String url = "http://api.linkedin.com/v1/people/~";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON********");
//This basic call profile in JSON format
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addHeader("x-li-format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON using query parameter********");
//This basic call profile in JSON format. Please note the call above is the preferred method.
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get my connections - going into a resource********");
//This basic call gets all your connections each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get only 10 connections - using parameters********");
//This basic call gets only 10 connections - each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
//more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("count", "10");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********GET network updates that are CONN and SHAR********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
//specifics on updates https://developer.linkedin.com/documents/network-update-types
url = "http://api.linkedin.com/v1/people/~/network/updates";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("type","SHAR");
request.addQuerystringParameter("type","CONN");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/people-search-api#Facets
//Why doesn't this look like
//people-search?title=developer&location=fr&industry=4
//url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("title", "Développeur");
request.addQuerystringParameter("facet", "industry,4");
request.addQuerystringParameter("facets", "location,industry");
System.out.println(request.getUrl());
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
/////////////////field selectors
System.out.println("********A basic user profile call with field selectors********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call with field selectors going into a subresource********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call into a subresource return data in JSON********");
//The ~ means yourself - so this should return the basic default information for your profile
//https://developer.linkedin.com/documents/field-selectors
url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A more complicated example using postings into groups********");
//https://developer.linkedin.com/documents/field-selectors
//https://developer.linkedin.com/documents/groups-api
url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();*/
/**************************
*
* Wrting to the LinkedIn API
*
**************************/
/*
* Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
* some code. Uncomment if you'd like to see writes in action.
*
*
System.out.println("********Write to the share - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "text/xml");
//Make an XML document
Document doc = DocumentHelper.createDocument();
Element share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
Element content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to Twitter - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addQuerystringParameter("twitter-post","true");
request.addHeader("Content-Type", "text/xml");
//Make an XML document
doc = DocumentHelper.createDocument();
share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to twitter - using JSON ********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
//NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
//set the headers to the server knows what we are sending
request.addHeader("Content-Type", "application/json");
request.addHeader("x-li-format", "json");
//make the json payload using json-simple
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("comment", "Posting from the API using JSON");
JSONObject contentObject = new JSONObject();
contentObject.put("title", "This is a another test post");
contentObject.put("submitted-url","http://www.linkedin.com");
contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
jsonMap.put("content", contentObject);
JSONObject visibilityObject = new JSONObject();
visibilityObject.put("code", "anyone");
jsonMap.put("visibility", visibilityObject);
request.addPayload(JSONValue.toJSONString(jsonMap));
service.signRequest(accessToken, request);
response = request.send();
//again no body - just headers
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
*/
/**************************
*
* Understanding the response, creating logging, request and response headers
*
**************************/
/*System.out.println();
System.out.println("********A basic user profile call and response dissected********");
//This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
//https://developer.linkedin.com/documents/debugging-api-calls
url = "https://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
//get all the headers
System.out.println("Request headers: " + request.getHeaders().toString());
System.out.println("Response headers: " + response.getHeaders().toString());
//url requested
System.out.println("Original location is: " + request.getHeaders().get("content-location"));
//Date of response
System.out.println("The datetime of the response is: " + response.getHeader("Date"));
//the format of the response
System.out.println("Format is: " + response.getHeader("x-li-format"));
//Content-type of the response
System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");
//get the HTTP response code - such as 200 or 404
int responseNumber = response.getCode();
if(responseNumber >= 199 && responseNumber < 300){
System.out.println("HOORAY IT WORKED!!");
System.out.println(response.getBody());
} else if (responseNumber >= 500 && responseNumber < 600){
//you could actually raise an exception here in your own code
System.out.println("Ruh Roh application error of type 500: " + responseNumber);
System.out.println(response.getBody());
} else if (responseNumber == 403){
System.out.println("A 403 was returned which usually means you have reached a throttle limit");
} else if (responseNumber == 401){
System.out.println("A 401 was returned which is a Oauth signature error");
System.out.println(response.getBody());
} else if (responseNumber == 405){
System.out.println("A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
}else {
System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums");
System.out.println(response.getBody());
}
System.out.println();System.out.println();
System.out.println("********A basic error logging function********");
// Now demonstrate how to make a logging function which provides us the info we need to
// properly help debug issues. Please use the logged block from here when requesting
// help in the forums.
url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
responseNumber = response.getCode();
if(responseNumber < 200 || responseNumber >= 300){
logDiagnostics(request, response);
} else {
System.out.println("You were supposed to submit a bad request");
}
System.out.println("******Finished******");
}
private static void logDiagnostics(OAuthRequest request, Response response){
System.out.println("\n\n[********************LinkedIn API Diagnostics**************************]\n");
System.out.println("Key: |-> " + API_KEY + " <-|");
System.out.println("\n|-> [******Sent*****] <-|");
System.out.println("Headers: |-> " + request.getHeaders().toString() + " <-|");
System.out.println("URL: |-> " + request.getUrl() + " <-|");
System.out.println("Query Params: |-> " + request.getQueryStringParams().toString() + " <-|");
System.out.println("Body Contents: |-> " + request.getBodyContents() + " <-|");
System.out.println("\n|-> [*****Received*****] <-|");
System.out.println("Headers: |-> " + response.getHeaders().toString() + " <-|");
System.out.println("Body: |-> " + response.getBody() + " <-|");
System.out.println("\n[******************End LinkedIn API Diagnostics************************]\n\n");
}*/
}
| smoothpanda1981/linkedin | java/src/com/linkedin/sample/Main.java | Java | apache-2.0 | 22,732 |
/*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pkware.truth.androidx.appcompat.widget;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.SearchView;
import androidx.cursoradapter.widget.CursorAdapter;
import com.google.common.truth.FailureMetadata;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Propositions for {@link SearchView} subjects.
*/
public class SearchViewSubject extends AbstractLinearLayoutCompatSubject<SearchView> {
@Nullable
private final SearchView actual;
public SearchViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable SearchView actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasImeOptions(int options) {
check("getImeOptions()").that(actual.getImeOptions()).isEqualTo(options);
}
public void hasInputType(int type) {
check("getInputType()").that(actual.getInputType()).isEqualTo(type);
}
public void hasMaximumWidth(int width) {
check("getMaxWidth()").that(actual.getMaxWidth()).isEqualTo(width);
}
public void hasQuery(@Nullable String query) {
check("getQuery()").that(actual.getQuery().toString()).isEqualTo(query);
}
public void hasQueryHint(@Nullable String hint) {
CharSequence actualHint = actual.getQueryHint();
String actualHintString;
if (actualHint == null) {
actualHintString = null;
} else {
actualHintString = actualHint.toString();
}
check("getQueryHint()").that(actualHintString).isEqualTo(hint);
}
public void hasQueryHint(@StringRes int resId) {
hasQueryHint(actual.getContext().getString(resId));
}
public void hasSuggestionsAdapter(@Nullable CursorAdapter adapter) {
check("getSuggestionsAdapter()").that(actual.getSuggestionsAdapter()).isSameInstanceAs(adapter);
}
public void isIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isTrue();
}
public void isNotIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isFalse();
}
public void isIconified() {
check("isIconified()").that(actual.isIconified()).isTrue();
}
public void isNotIconified() {
check("isIconified()").that(actual.isIconified()).isFalse();
}
public void isQueryRefinementEnabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isTrue();
}
public void isQueryRefinementDisabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isFalse();
}
public void isSubmitButtonEnabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isTrue();
}
public void isSubmitButtonDisabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isFalse();
}
}
| pkware/truth-android | truth-android-appcompat/src/main/java/com/pkware/truth/androidx/appcompat/widget/SearchViewSubject.java | Java | apache-2.0 | 3,403 |
/*
JustMock Lite
Copyright © 2010-2015 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core;
namespace Telerik.JustMock.Core
{
internal static class ExpressionUtil
{
public static object EvaluateExpression(this Expression expr)
{
while (expr.NodeType == ExpressionType.Convert)
{
var unary = expr as UnaryExpression;
if (unary.Type.IsAssignableFrom(unary.Operand.Type))
expr = unary.Operand;
else break;
}
var constant = expr as ConstantExpression;
if (constant != null)
return constant.Value;
bool canCallGetField = true;
#if COREFX
canCallGetField = ProfilerInterceptor.IsProfilerAttached;
#endif
if (canCallGetField)
{
var memberAccess = expr as MemberExpression;
if (memberAccess != null)
{
var asField = memberAccess.Member as FieldInfo;
if (asField != null)
{
return SecuredReflectionMethods.GetField(asField, memberAccess.Expression != null
? memberAccess.Expression.EvaluateExpression() : null);
}
}
}
#if !DOTNET35
var listInit = expr as ListInitExpression;
if (listInit != null)
{
var collection = Expression.Variable(listInit.NewExpression.Type);
var block = new List<Expression>
{
Expression.Assign(collection, listInit.NewExpression)
};
block.AddRange(listInit.Initializers.Select(init => Expression.Call(collection, init.AddMethod, init.Arguments.ToArray())));
block.Add(collection);
expr = Expression.Block(new[] { collection }, block.ToArray());
}
#endif
var lambda = Expression.Lambda(Expression.Convert(expr, typeof(object)));
var delg = (Func<object>)lambda.Compile();
return ProfilerInterceptor.GuardExternal(delg);
}
public static object[] GetArgumentsFromConstructorExpression(this LambdaExpression expression)
{
var newExpr = (NewExpression)expression.Body;
return newExpr.Arguments.Select(arg => arg.EvaluateExpression()).ToArray();
}
public static string ConvertMockExpressionToString(Expression expr)
{
string result = expr.Type.ToString();
var replacer = new ClosureWithSafeParameterReplacer();
var lambda = expr as LambdaExpression;
if (lambda != null)
expr = lambda.Body;
expr = replacer.Visit(expr);
var cleanedExpr = MakeVoidLambda(expr, replacer.Parameters);
result = cleanedExpr.ToString();
result = replacer.CleanExpressionString(result);
return result;
}
private static LambdaExpression MakeVoidLambda(Expression body, List<ParameterExpression> parameters)
{
Type delegateType = null;
switch (parameters.Count)
{
case 0: delegateType = typeof(Action); break;
case 1: delegateType = typeof(Action<>); break;
case 2: delegateType = typeof(Action<,>); break;
case 3: delegateType = typeof(Action<,,>); break;
case 4: delegateType = typeof(Action<,,,>); break;
default:
delegateType = typeof(ExpressionUtil).Assembly.GetType("Telerik.JustMock.Action`" + parameters.Count);
break;
}
if (delegateType != null)
{
if (delegateType.IsGenericTypeDefinition)
{
delegateType = delegateType.MakeGenericType(parameters.Select(p => p.Type).ToArray());
}
return Expression.Lambda(delegateType, body, parameters.ToArray());
}
else
return Expression.Lambda(body, parameters.ToArray());
}
private class ClosureWithSafeParameterReplacer : Telerik.JustMock.Core.Expressions.ExpressionVisitor
{
public readonly List<ParameterExpression> Parameters = new List<ParameterExpression>();
public readonly Dictionary<string, string> ReplacementValues = new Dictionary<string, string>();
private readonly Dictionary<object, string> stringReplacements = new Dictionary<object, string>(ReferenceEqualityComparer<object>.Instance);
private bool hasMockReplacement;
protected override Expression VisitConstant(ConstantExpression c)
{
if (c.Type.IsCompilerGenerated())
return Expression.Parameter(c.Type, "__compiler_generated__");
if (!hasMockReplacement && c.Type.IsProxy() || (c.Value != null && c.Value.GetType().IsProxy()))
{
hasMockReplacement = true;
var param = Expression.Parameter(c.Type, "x");
this.Parameters.Add(param);
return param;
}
if (c.Value != null)
{
string name;
var value = c.Value;
if (!this.stringReplacements.TryGetValue(value, out name))
{
name = String.Format("__string_replacement_{0}__", this.stringReplacements.Count);
this.stringReplacements.Add(value, name);
var valueStr = "<Exception>";
try
{
valueStr = ProfilerInterceptor.GuardExternal(() => value.ToString());
}
catch { }
if (String.IsNullOrEmpty(valueStr))
{
valueStr = "#" + this.stringReplacements.Count;
}
this.ReplacementValues.Add(name, valueStr);
}
var param = Expression.Parameter(c.Type, name);
this.Parameters.Add(param);
return param;
}
return base.VisitConstant(c);
}
public string CleanExpressionString(string result)
{
result = result.Replace("__compiler_generated__.", "");
foreach (var strReplacement in this.ReplacementValues.Keys)
{
result = result.Replace(strReplacement, '(' + this.ReplacementValues[strReplacement] + ')');
}
return result;
}
}
}
}
| telerik/JustMockLite | Telerik.JustMock/Core/ExpressionUtil.cs | C# | apache-2.0 | 6,015 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.am0e.jbeans;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
/** Represents a field that can be accessed directly if the field is public or via an associated getter or
* setter.
* The class provides a getter and a setter to set the associated field value in an object.
*
* @author Anthony (ARPT)
*/
/**
* @author anthony
*
*/
public final class FieldInfo implements BaseInfo {
/**
* Field name
*/
final String name;
/**
* Field name hashcode.
*/
final int hash;
/**
* The bean field.
*/
final Field field;
/**
* Optional setter method. If this field is public, this will contain null.
*/
final MethodInfo setter;
/**
* Optional getter method. If this field is public, this will contain null.
*/
final MethodInfo getter;
/**
* If the field is a parameterized List or Map, this field will contain the
* class type of the value stored in the list or map. in the parameter. Eg:
* List<String> it will contain String. For Map<String,Double>
* it will contain Double.
*/
final Class<?> actualType;
FieldInfo(Field field, MethodInfo getter, MethodInfo setter) {
// Get the type of the field.
//
this.actualType = BeanUtils.getActualTypeFromMethodOrField(null, field);
this.field = field;
this.setter = setter;
this.getter = getter;
this.name = field.getName().intern();
this.hash = this.name.hashCode();
}
public Field getField() {
return field;
}
public Class<?> getType() {
return field.getType();
}
public Class<?> getActualType() {
return actualType;
}
public String getName() {
return name;
}
public String toString() {
return field.getDeclaringClass().getName() + "#" + name;
}
public boolean isField() {
return field == null ? false : true;
}
/**
* Returns true if the field value can be retrieved either through the
* public field itself or through a public getter method.
*/
public final boolean isReadable() {
return (Modifier.isPublic(field.getModifiers()) || getter != null);
}
public final boolean isSettable() {
return (Modifier.isPublic(field.getModifiers()) || setter != null);
}
public final boolean isTransient() {
return (Modifier.isTransient(field.getModifiers()));
}
public final Object callGetter(Object bean) throws BeanException {
if (bean == null)
return null;
// If the field is public, get the value directly.
//
try {
if (getter != null) {
// Use the public getter. We will always attempt to use this
// FIRST!!
//
return getter.method.invoke(bean);
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not gettable", bean, getName(), null);
}
return field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callGetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
public final void callSetter(Object bean, Object value) throws BeanException {
value = BeanUtils.cast(value, field.getType());
try {
// Use the public setter. We will always attempt to use this FIRST!!
//
if (setter != null) {
setter.method.invoke(bean, value);
return;
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not settable", bean, getName(), null);
}
// If the field is public, set the value directly.
//
field.set(bean, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callSetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
/**
* Converts a value into a value of the bean type.
*
* @param value
* The value to convert.
* @return If the value could not be converted, the value itself is
* returned. For example: if (beanField.valueOf(strVal)==strVal)
* throw new IllegalArgumentException();
*/
public final Object valueOf(Object value) {
return BeanUtils.cast(value, actualType);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> type) {
return field.getAnnotation(type);
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> type) {
return field.getAnnotation(type) == null ? false : true;
}
@Override
public MethodHandle getHandle(Lookup lookup, boolean setter) {
try {
if (setter)
return lookup.findSetter(field.getDeclaringClass(), name, field.getType());
else
return lookup.findGetter(field.getDeclaringClass(), name, field.getType());
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanException(e);
}
}
@Override
public String makeSignature(StringBuilder sb) {
sb.setLength(0);
sb.append(getType().toString());
sb.append(' ');
sb.append(getName());
return sb.toString();
}
}
| am0e/commons | src/main/java/com/github/am0e/jbeans/FieldInfo.java | Java | apache-2.0 | 7,111 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
'''
Created on 16/04/2013
@author: henar
'''
import httplib
import sys
import os
from xml.dom.minidom import parse, parseString
from xml.dom.minidom import getDOMImplementation
from xml.etree.ElementTree import Element, SubElement, tostring
import md5
import httplib, urllib
import utils
token = utils.obtainToken(keystone_ip, keystone_port, user, password, project)
print(token)
headers = {'Content-Type': 'application/xml', 'X-Auth-Token': token, 'Tenant-ID': vdc}
print(headers)
print('Get products in the software catalogue: ')
resource = "/sdc/rest/catalog/product"
data1 = utils.doRequestHttpOperation(domine, port, resource, 'GET', None, headers)
dom = parseString(data1)
try:
product = (dom.getElementsByTagName('product'))[0]
productname = product.firstChild.firstChild.nodeValue
print('First product in the software catalogue: ' + productname)
except:
print ("Error in the request to get products")
sys.exit(1)
print('Get Product Details ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name, 'GET', None, headers)
print(" OK")
print('Get Product Releases ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + "/release", 'GET',
None, headers)
print(" OK")
print('Get Product Release Info ' + product_name + " " + product_version )
data1 = utils.doRequestHttpOperation(domine, port,
"/sdc/rest/catalog/product/" + product_name + "/release/" + product_version, 'GET', None, headers)
print(" OK")
print('Get Product Attributes ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + '/attributes', 'GET',
None, headers)
print(" OK")
resource_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance"
print('Install a product in VM. Product ' + product_name )
productInstanceDto = utils.createProductInstanceDto(vm_ip, vm_fqn, product_name, product_version)
print (tostring(productInstanceDto))
task = utils.doRequestHttpOperation(domine, port, resource_product_instance, 'POST', tostring(productInstanceDto),
headers)
print (task)
status = utils.processTask(domine, port, task)
print (" " + status)
resource_get_info_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Product Instance Info. Product ' + product_name )
data = utils.doRequestHttpOperation(domine, port, resource_get_info_product_instance, 'GET', None)
print(data)
status = utils.processProductInstanceStatus(data)
#if status != 'INSTALLED':
# print("Status not correct" + status)
resource_delete_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Delete Product Instance ' + product_name )
task = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'DELETE', None)
status = utils.processTask(domine, port, task)
print(" OK")
data = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'GET', None)
statusProduct = utils.processProductInstanceStatus(data)
#if status != 'UNINSTALLED':
# print("Status not correct" + statusProduct)
| telefonicaid/fiware-sdc | automatization_scripts/get_software_catalogue.py | Python | apache-2.0 | 4,111 |
var interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder =
[
[ "getPacketsReceived", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#a190993a33fa895f9d07145f3a04f5d22", null ],
[ "getPacketsSent", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#ae9a71f2c48c5430a348eba326eb6d112", null ],
[ "getPort", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#af9c20290d571c3f0b6bf99f28ffc4005", null ]
]; | onosfw/apis | onos/apis/interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.js | JavaScript | apache-2.0 | 512 |
<?php
defined('SYSTEM_IN') or exit('Access Denied');
hasrule('weixin','weixin');
$operation = !empty($_GP['op']) ? $_GP['op'] : 'display';
if($operation=='detail')
{
if(!empty($_GP['id']))
{
$rule = mysqld_select('SELECT * FROM '.table('weixin_rule')." WHERE id = :id" , array(':id' =>intval($_GP['id'])));
}
if(checksubmit())
{
if(empty($_GP['id']))
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'thumb'=>$thumb,'description'=>$_GP['description'],'url'=>$_GP['url']);
mysqld_insert('weixin_rule', $data);
message('保存成功!', 'refresh', 'success');
}else
{
if($rule['keywords']!=$_GP['keywords'])
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'description'=>$_GP['description'],'url'=>$_GP['url']);
if(!empty($thumb))
{
$data['thumb']=$thumb;
}
mysqld_update('weixin_rule', $data, array('id' => $_GP['id']));
message('修改成功!', 'refresh', 'success');
}
}
include page('rule_detail');
exit;
}
if($operation=='delete'&&!empty($_GP['id']))
{
mysqld_delete('weixin_rule', array('id'=>$_GP['id']));
message('删除成功!', 'refresh', 'success');
}
$list=mysqld_selectall('SELECT * FROM '.table('weixin_rule'));
include page('rule'); | jaydom/weishang | system/weixin/class/web/rule.php | PHP | apache-2.0 | 3,054 |
package org.corpus_tools.annis.gui.visualizers.component.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.corpus_tools.annis.gui.visualizers.VisualizerInput;
import org.corpus_tools.annis.gui.visualizers.component.tree.AnnisGraphTools;
import org.corpus_tools.salt.SaltFactory;
import org.corpus_tools.salt.common.SDominanceRelation;
import org.corpus_tools.salt.core.SAnnotation;
import org.junit.jupiter.api.Test;
class AnnisGraphToolsTest {
@Test
void extractAnnotation() {
assertNull(AnnisGraphTools.extractAnnotation(null, "some_ns", "func"));
Set<SAnnotation> annos = new LinkedHashSet<>();
SAnnotation annoFunc = SaltFactory.createSAnnotation();
annoFunc.setNamespace("some_ns");
annoFunc.setName("func");
annoFunc.setValue("value");
annos.add(annoFunc);
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, null, "func"));
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, "some_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "some_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, null, "anno"));
}
@Test
void isTerminalNullCheck() {
assertFalse(AnnisGraphTools.isTerminal(null, null));
VisualizerInput mockedVisInput = mock(VisualizerInput.class);
assertFalse(AnnisGraphTools.isTerminal(null, mockedVisInput));
}
@Test
void hasEdgeSubtypeForEmptyType() {
SDominanceRelation rel1 = mock(SDominanceRelation.class);
VisualizerInput input = mock(VisualizerInput.class);
// When the type is empty, this should be treated like having no type (null) at all
when(rel1.getType()).thenReturn("");
Map<String, String> mappings = new LinkedHashMap<>();
when(input.getMappings()).thenReturn(mappings);
mappings.put("edge_type", "null");
AnnisGraphTools tools = new AnnisGraphTools(input);
assertTrue(tools.hasEdgeSubtype(rel1, "null"));
SDominanceRelation rel2 = mock(SDominanceRelation.class);
when(rel1.getType()).thenReturn(null);
assertTrue(tools.hasEdgeSubtype(rel2, "null"));
}
}
| korpling/ANNIS | src/test/java/org/corpus_tools/annis/gui/visualizers/component/tree/AnnisGraphToolsTest.java | Java | apache-2.0 | 2,637 |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2006/08/21 Martin D. Flynn
// Initial release
// ----------------------------------------------------------------------------
package org.opengts.dbtypes;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.io.*;
import java.sql.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
public class DTIPAddress
extends DBFieldType
{
// ------------------------------------------------------------------------
private IPTools.IPAddress ipAddr = null;
public DTIPAddress(IPTools.IPAddress ipAddr)
{
this.ipAddr = ipAddr;
}
public DTIPAddress(String ipAddr)
{
super(ipAddr);
this.ipAddr = new IPTools.IPAddress(ipAddr);
}
public DTIPAddress(ResultSet rs, String fldName)
throws SQLException
{
super(rs, fldName);
// set to default value if 'rs' is null
this.ipAddr = (rs != null)? new IPTools.IPAddress(rs.getString(fldName)) : null;
}
// ------------------------------------------------------------------------
public boolean isMatch(String ipAddr)
{
if (this.ipAddr != null) {
return this.ipAddr.isMatch(ipAddr);
} else {
return true;
}
}
// ------------------------------------------------------------------------
public Object getObject()
{
return this.toString();
}
public String toString()
{
return (this.ipAddr != null)? this.ipAddr.toString() : "";
}
// ------------------------------------------------------------------------
public boolean equals(Object other)
{
if (this == other) {
// same object
return true;
} else
if (other instanceof DTIPAddress) {
DTIPAddress otherList = (DTIPAddress)other;
if (otherList.ipAddr == this.ipAddr) {
// will also match if both are null
return true;
} else
if ((this.ipAddr == null) || (otherList.ipAddr == null)) {
// one is null, the other isn't
return false;
} else {
// IPAddressList match
return this.ipAddr.equals(otherList.ipAddr);
}
} else {
return false;
}
}
// ------------------------------------------------------------------------
}
| CASPED/OpenGTS | src/org/opengts/dbtypes/DTIPAddress.java | Java | apache-2.0 | 3,318 |
package ru.stqa.pft.mantis.appmanager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import ru.stqa.pft.mantis.model.User;
import java.util.List;
/**
* Created by Даниил on 11.06.2017.
*/
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
public User getUser() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<User> result = session.createQuery("from User").list();
session.getTransaction().commit();
session.close();
return result.stream().filter((s)->(!s.getUsername().equals("administrator"))).iterator().next();
}
}
| SweetyDonut/java_pft | Mantis_tests/src/test/java/ru/stqa/pft/mantis/appmanager/DbHelper.java | Java | apache-2.0 | 1,105 |
package com.mricefox.androidhorizontalcalendar.library.calendar;
import android.database.Observable;
/**
* Author:zengzifeng email:zeng163mail@163.com
* Description:
* Date:2015/12/25
*/
public class DataSetObservable extends Observable<DataSetObserver> {
public boolean hasObservers() {
synchronized (mObservers) {
return !mObservers.isEmpty();
}
}
public void notifyChanged() {
synchronized (mObservers) {//mObservers register and notify maybe in different thread
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
public void notifyItemRangeChanged(long from, long to) {
synchronized (mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(from, to);
}
}
}
}
| MrIceFox/AndroidHorizontalCalendar | library/src/main/java/com/mricefox/androidhorizontalcalendar/library/calendar/DataSetObservable.java | Java | apache-2.0 | 918 |
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.classfile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.ceylon.langtools.classfile.TypeAnnotation.Position.TypePathEntry;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class TypeAnnotation {
TypeAnnotation(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
constant_pool = cr.getConstantPool();
position = read_position(cr);
annotation = new Annotation(cr);
}
public TypeAnnotation(ConstantPool constant_pool,
Annotation annotation, Position position) {
this.constant_pool = constant_pool;
this.position = position;
this.annotation = annotation;
}
public int length() {
int n = annotation.length();
n += position_length(position);
return n;
}
@Override
public String toString() {
try {
return "@" + constant_pool.getUTF8Value(annotation.type_index).toString().substring(1) +
" pos: " + position.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
public final ConstantPool constant_pool;
public final Position position;
public final Annotation annotation;
private static Position read_position(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
// Copied from ClassReader
int tag = cr.readUnsignedByte(); // TargetType tag is a byte
if (!TargetType.isValidTargetTypeValue(tag))
throw new Annotation.InvalidAnnotation("TypeAnnotation: Invalid type annotation target type value: " + String.format("0x%02X", tag));
TargetType type = TargetType.fromTargetTypeValue(tag);
Position position = new Position();
position.type = type;
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
position.offset = cr.readUnsignedShort();
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = cr.readUnsignedShort();
position.lvarOffset = new int[table_length];
position.lvarLength = new int[table_length];
position.lvarIndex = new int[table_length];
for (int i = 0; i < table_length; ++i) {
position.lvarOffset[i] = cr.readUnsignedShort();
position.lvarLength[i] = cr.readUnsignedShort();
position.lvarIndex[i] = cr.readUnsignedShort();
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
position.exception_index = cr.readUnsignedShort();
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
position.parameter_index = cr.readUnsignedByte();
position.bound_index = cr.readUnsignedByte();
break;
// class extends or implements clause
case CLASS_EXTENDS:
int in = cr.readUnsignedShort();
if (in == 0xFFFF)
in = -1;
position.type_index = in;
break;
// throws
case THROWS:
position.type_index = cr.readUnsignedShort();
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
position.offset = cr.readUnsignedShort();
position.type_index = cr.readUnsignedByte();
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + type);
}
{ // Write type path
int len = cr.readUnsignedByte();
List<Integer> loc = new ArrayList<Integer>(len);
for (int i = 0; i < len * TypePathEntry.bytesPerEntry; ++i)
loc.add(cr.readUnsignedByte());
position.location = Position.getTypePathFromBinary(loc);
}
return position;
}
private static int position_length(Position pos) {
int n = 0;
n += 1; // TargetType tag is a byte
switch (pos.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
n += 2; // offset
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
n += 2; // table_length;
int table_length = pos.lvarOffset.length;
n += 2 * table_length; // offset
n += 2 * table_length; // length
n += 2 * table_length; // index
break;
// exception parameter
case EXCEPTION_PARAMETER:
n += 2; // exception_index
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
n += 1; // parameter_index
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
n += 1; // parameter_index
n += 1; // bound_index
break;
// class extends or implements clause
case CLASS_EXTENDS:
n += 2; // type_index
break;
// throws
case THROWS:
n += 2; // type_index
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
n += 1; // parameter_index
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
n += 2; // offset
n += 1; // type index
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + pos.type);
}
{
n += 1; // length
n += TypePathEntry.bytesPerEntry * pos.location.size(); // bytes for actual array
}
return n;
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TypeAnnotationPosition
public static class Position {
public enum TypePathEntryKind {
ARRAY(0),
INNER_TYPE(1),
WILDCARD(2),
TYPE_ARGUMENT(3);
public final int tag;
private TypePathEntryKind(int tag) {
this.tag = tag;
}
}
public static class TypePathEntry {
/** The fixed number of bytes per TypePathEntry. */
public static final int bytesPerEntry = 2;
public final TypePathEntryKind tag;
public final int arg;
public static final TypePathEntry ARRAY = new TypePathEntry(TypePathEntryKind.ARRAY);
public static final TypePathEntry INNER_TYPE = new TypePathEntry(TypePathEntryKind.INNER_TYPE);
public static final TypePathEntry WILDCARD = new TypePathEntry(TypePathEntryKind.WILDCARD);
private TypePathEntry(TypePathEntryKind tag) {
if (!(tag == TypePathEntryKind.ARRAY ||
tag == TypePathEntryKind.INNER_TYPE ||
tag == TypePathEntryKind.WILDCARD)) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = 0;
}
public TypePathEntry(TypePathEntryKind tag, int arg) {
if (tag != TypePathEntryKind.TYPE_ARGUMENT) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = arg;
}
public static TypePathEntry fromBinary(int tag, int arg) {
if (arg != 0 && tag != TypePathEntryKind.TYPE_ARGUMENT.tag) {
throw new AssertionError("Invalid TypePathEntry tag/arg: " + tag + "/" + arg);
}
switch (tag) {
case 0:
return ARRAY;
case 1:
return INNER_TYPE;
case 2:
return WILDCARD;
case 3:
return new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT, arg);
default:
throw new AssertionError("Invalid TypePathEntryKind tag: " + tag);
}
}
@Override
public String toString() {
return tag.toString() +
(tag == TypePathEntryKind.TYPE_ARGUMENT ? ("(" + arg + ")") : "");
}
@Override
public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) {
return false;
}
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
}
@Override
public int hashCode() {
return this.tag.hashCode() * 17 + this.arg;
}
}
public TargetType type = TargetType.UNKNOWN;
// For generic/array types.
// TODO: or should we use null? Noone will use this object.
public List<TypePathEntry> location = new ArrayList<TypePathEntry>(0);
// Tree position.
public int pos = -1;
// For typecasts, type tests, new (and locals, as start_pc).
public boolean isValidOffset = false;
public int offset = -1;
// For locals. arrays same length
public int[] lvarOffset = null;
public int[] lvarLength = null;
public int[] lvarIndex = null;
// For type parameter bound
public int bound_index = Integer.MIN_VALUE;
// For type parameter and method parameter
public int parameter_index = Integer.MIN_VALUE;
// For class extends, implements, and throws clauses
public int type_index = Integer.MIN_VALUE;
// For exception parameters, index into exception table
public int exception_index = Integer.MIN_VALUE;
public Position() {}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(type);
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
sb.append(", offset = ");
sb.append(offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
if (lvarOffset == null) {
sb.append(", lvarOffset is null!");
break;
}
sb.append(", {");
for (int i = 0; i < lvarOffset.length; ++i) {
if (i != 0) sb.append("; ");
sb.append("start_pc = ");
sb.append(lvarOffset[i]);
sb.append(", length = ");
sb.append(lvarLength[i]);
sb.append(", index = ");
sb.append(lvarIndex[i]);
}
sb.append("}");
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
sb.append(", param_index = ");
sb.append(parameter_index);
sb.append(", bound_index = ");
sb.append(bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// throws
case THROWS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// exception parameter
case EXCEPTION_PARAMETER:
sb.append(", exception_index = ");
sb.append(exception_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
sb.append(", offset = ");
sb.append(offset);
sb.append(", type_index = ");
sb.append(type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
sb.append(", position UNKNOWN!");
break;
default:
throw new AssertionError("Unknown target type: " + type);
}
// Append location data for generics/arrays.
if (!location.isEmpty()) {
sb.append(", location = (");
sb.append(location);
sb.append(")");
}
sb.append(", pos = ");
sb.append(pos);
sb.append(']');
return sb.toString();
}
/**
* Indicates whether the target tree of the annotation has been optimized
* away from classfile or not.
* @return true if the target has not been optimized away
*/
public boolean emitToClassfile() {
return !type.isLocal() || isValidOffset;
}
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
*
* @param list The bytecode representation of the type path.
*/
public static List<TypePathEntry> getTypePathFromBinary(List<Integer> list) {
List<TypePathEntry> loc = new ArrayList<TypePathEntry>(list.size() / TypePathEntry.bytesPerEntry);
int idx = 0;
while (idx < list.size()) {
if (idx + 1 == list.size()) {
throw new AssertionError("Could not decode type path: " + list);
}
loc.add(TypePathEntry.fromBinary(list.get(idx), list.get(idx + 1)));
idx += 2;
}
return loc;
}
public static List<Integer> getBinaryFromTypePath(List<TypePathEntry> locs) {
List<Integer> loc = new ArrayList<Integer>(locs.size() * TypePathEntry.bytesPerEntry);
for (TypePathEntry tpe : locs) {
loc.add(tpe.tag.tag);
loc.add(tpe.arg);
}
return loc;
}
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TargetType
// The IsLocal flag could be removed here.
public enum TargetType {
/** For annotations on a class type parameter declaration. */
CLASS_TYPE_PARAMETER(0x00),
/** For annotations on a method type parameter declaration. */
METHOD_TYPE_PARAMETER(0x01),
/** For annotations on the type of an "extends" or "implements" clause. */
CLASS_EXTENDS(0x10),
/** For annotations on a bound of a type parameter of a class. */
CLASS_TYPE_PARAMETER_BOUND(0x11),
/** For annotations on a bound of a type parameter of a method. */
METHOD_TYPE_PARAMETER_BOUND(0x12),
/** For annotations on a field. */
FIELD(0x13),
/** For annotations on a method return type. */
METHOD_RETURN(0x14),
/** For annotations on the method receiver. */
METHOD_RECEIVER(0x15),
/** For annotations on a method parameter. */
METHOD_FORMAL_PARAMETER(0x16),
/** For annotations on a throws clause in a method declaration. */
THROWS(0x17),
/** For annotations on a local variable. */
LOCAL_VARIABLE(0x40, true),
/** For annotations on a resource variable. */
RESOURCE_VARIABLE(0x41, true),
/** For annotations on an exception parameter. */
EXCEPTION_PARAMETER(0x42, true),
/** For annotations on a type test. */
INSTANCEOF(0x43, true),
/** For annotations on an object creation expression. */
NEW(0x44, true),
/** For annotations on a constructor reference receiver. */
CONSTRUCTOR_REFERENCE(0x45, true),
/** For annotations on a method reference receiver. */
METHOD_REFERENCE(0x46, true),
/** For annotations on a typecast. */
CAST(0x47, true),
/** For annotations on a type argument of an object creation expression. */
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(0x48, true),
/** For annotations on a type argument of a method call. */
METHOD_INVOCATION_TYPE_ARGUMENT(0x49, true),
/** For annotations on a type argument of a constructor reference. */
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(0x4A, true),
/** For annotations on a type argument of a method reference. */
METHOD_REFERENCE_TYPE_ARGUMENT(0x4B, true),
/** For annotations with an unknown target. */
UNKNOWN(0xFF);
private static final int MAXIMUM_TARGET_TYPE_VALUE = 0x4B;
private final int targetTypeValue;
private final boolean isLocal;
private TargetType(int targetTypeValue) {
this(targetTypeValue, false);
}
private TargetType(int targetTypeValue, boolean isLocal) {
if (targetTypeValue < 0
|| targetTypeValue > 255)
throw new AssertionError("Attribute type value needs to be an unsigned byte: " + String.format("0x%02X", targetTypeValue));
this.targetTypeValue = targetTypeValue;
this.isLocal = isLocal;
}
/**
* Returns whether or not this TargetType represents an annotation whose
* target is exclusively a tree in a method body
*
* Note: wildcard bound targets could target a local tree and a class
* member declaration signature tree
*/
public boolean isLocal() {
return isLocal;
}
public int targetTypeValue() {
return this.targetTypeValue;
}
private static final TargetType[] targets;
static {
targets = new TargetType[MAXIMUM_TARGET_TYPE_VALUE + 1];
TargetType[] alltargets = values();
for (TargetType target : alltargets) {
if (target.targetTypeValue != UNKNOWN.targetTypeValue)
targets[target.targetTypeValue] = target;
}
for (int i = 0; i <= MAXIMUM_TARGET_TYPE_VALUE; ++i) {
if (targets[i] == null)
targets[i] = UNKNOWN;
}
}
public static boolean isValidTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return true;
return (tag >= 0 && tag < targets.length);
}
public static TargetType fromTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return UNKNOWN;
if (tag < 0 || tag >= targets.length)
throw new AssertionError("Unknown TargetType: " + tag);
return targets[tag];
}
}
}
| ceylon/ceylon | langtools-classfile/src/org/eclipse/ceylon/langtools/classfile/TypeAnnotation.java | Java | apache-2.0 | 23,331 |
define([
"settings",
"views/tags"
], function(panelSettings, TagsView) {
var PanelFileView = codebox.require("views/panels/file");
var PanelOutlineView = PanelFileView.extend({
className: "cb-panel-outline",
FileView: TagsView
});
return PanelOutlineView;
}); | cethap/cbcompiled | addons/cb.panel.outline/views/panel.js | JavaScript | apache-2.0 | 301 |
package com.ticktick.testimagecropper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.ticktick.imagecropper.CropImageActivity;
import com.ticktick.imagecropper.CropIntent;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 0x1;
public static final int REQUEST_CODE_IMAGE_CROPPER = 0x2;
public static final String CROPPED_IMAGE_FILEPATH = "/sdcard/test.jpg";
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.CroppedImageView);
}
public void onClickButton(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_CODE_PICK_IMAGE);
}
public void startCropImage( Uri uri ) {
Intent intent = new Intent(this,CropImageActivity.class);
intent.setData(uri);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(CROPPED_IMAGE_FILEPATH)));
//intent.putExtra("aspectX",2);
//intent.putExtra("aspectY",1);
//intent.putExtra("outputX",320);
//intent.putExtra("outputY",240);
//intent.putExtra("maxOutputX",640);
//intent.putExtra("maxOutputX",480);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CROPPER);
}
public void startCropImageByCropIntent( Uri uri ) {
CropIntent intent = new CropIntent();
intent.setImagePath(uri);
intent.setOutputPath(CROPPED_IMAGE_FILEPATH);
//intent.setAspect(2, 1);
//intent.setOutputSize(480,320);
//intent.setMaxOutputSize(480,320);
startActivityForResult(intent.getIntent(this), REQUEST_CODE_IMAGE_CROPPER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if( requestCode == REQUEST_CODE_PICK_IMAGE ) {
startCropImage(data.getData());
}
else if( requestCode == REQUEST_CODE_IMAGE_CROPPER ) {
Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
InputStream in = null;
try {
in = getContentResolver().openInputStream(croppedUri);
Bitmap b = BitmapFactory.decodeStream(in);
mImageView.setImageBitmap(b);
Toast.makeText(this,"Crop success,saved at"+CROPPED_IMAGE_FILEPATH,Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| msdgwzhy6/ImageCropper | TestImageCropper/src/com/ticktick/testimagecropper/MainActivity.java | Java | apache-2.0 | 3,086 |
<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo CHtml::label('Pin','pin'); ?>
<?php echo CHtml::passwordField('pin'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
<!--
<p class="hint">
Hint: You may login with <tt>demo/demo</tt>.
</p>
-->
</div>
<!--
<div class="row rememberMe">
<?php //echo $form->checkBox($model,'rememberMe'); ?>
<?php //echo $form->label($model,'rememberMe'); ?>
<?php //echo $form->error($model,'rememberMe'); ?>
</div>
-->
<div class="row submit">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
| fipumjdeveloper/web | views/site/login.php | PHP | apache-2.0 | 1,309 |
/*
* 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.felix.deploymentadmin;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import org.osgi.framework.Version;
import org.osgi.service.deploymentadmin.BundleInfo;
import org.osgi.service.deploymentadmin.DeploymentException;
/**
* Implementation of the <code>BundleInfo</code> interface as defined by the OSGi mobile specification.
*/
public class BundleInfoImpl extends AbstractInfo implements BundleInfo {
private final Version m_version;
private final String m_symbolicName;
private final boolean m_customizer;
/**
* Creates an instance of this class.
*
* @param path The path / resource-id of the bundle resource.
* @param attributes Set of attributes describing the bundle resource.
* @throws DeploymentException If the specified attributes do not describe a valid bundle.
*/
public BundleInfoImpl(String path, Attributes attributes) throws DeploymentException {
super(path, attributes);
String bundleSymbolicName = attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME);
if (bundleSymbolicName == null) {
throw new DeploymentException(DeploymentException.CODE_MISSING_HEADER, "Missing '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else if (bundleSymbolicName.trim().equals("")) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else {
m_symbolicName = parseSymbolicName(bundleSymbolicName);
}
String version = attributes.getValue(org.osgi.framework.Constants.BUNDLE_VERSION);
if (version == null || version == "") {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
try {
m_version = Version.parseVersion(version);
} catch (IllegalArgumentException e) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
m_customizer = parseBooleanHeader(attributes, Constants.DEPLOYMENTPACKAGE_CUSTOMIZER);
}
/**
* Strips parameters from the bundle symbolic name such as "foo;singleton:=true".
*
* @param name full name as found in the manifest of the deployment package
* @return name without parameters
*/
private String parseSymbolicName(String name) {
// note that we don't explicitly check if there are tokens, because that
// check has already been made before we are invoked here
StringTokenizer st = new StringTokenizer(name, ";");
return st.nextToken();
}
public String getSymbolicName() {
return m_symbolicName;
}
public Version getVersion() {
return m_version;
}
/**
* Determine whether this bundle resource is a customizer bundle.
*
* @return True if the bundle is a customizer bundle, false otherwise.
*/
public boolean isCustomizer() {
return m_customizer;
}
/**
* Verify if the specified attributes describe a bundle resource.
*
* @param attributes Attributes describing the resource
* @return true if the attributes describe a bundle resource, false otherwise
*/
public static boolean isBundleResource(Attributes attributes) {
return (attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) != null);
}
}
| boneman1231/org.apache.felix | trunk/deploymentadmin/deploymentadmin/src/main/java/org/apache/felix/deploymentadmin/BundleInfoImpl.java | Java | apache-2.0 | 4,581 |
# Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
| yaybu/touchdown | touchdown/aws/ec2/instance.py | Python | apache-2.0 | 4,911 |
package com.zlwh.hands.api.domain.base;
public class PageDomain {
private String pageNo;
private String pageSize = "15";
private long pageTime; // 上次刷新时间,分页查询时,防止分页数据错乱
public String getPageNo() {
return pageNo;
}
public void setPageNo(String pageNo) {
this.pageNo = pageNo;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public long getPageTime() {
return pageTime;
}
public void setPageTime(long pageTime) {
this.pageTime = pageTime;
}
}
| javyuan/jeesite-api | src/main/java/com/zlwh/hands/api/domain/base/PageDomain.java | Java | apache-2.0 | 593 |
package io.github.thankpoint.security.impl;
import java.security.Provider;
import java.security.Security;
import io.github.thankpoint.security.api.provider.SecurityProviderBuilder;
/**
* Implementation of {@link SecurityProviderBuilder}.
*
* @param <B> type of the returned builder.
* @author thks
*/
public interface AbstractSecurityProviderBuilderImpl<B> extends SecurityProviderBuilder<B> {
@Override
default B provider() {
return provider((Provider) null);
}
@Override
default B provider(String name) {
return provider(Security.getProvider(name));
}
}
| thankpoint/thanks4java | security/src/main/java/io/github/thankpoint/security/impl/AbstractSecurityProviderBuilderImpl.java | Java | apache-2.0 | 589 |
package com.github.saulis.enumerables;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
| Saulis/enumerables | src/main/java/com/github/saulis/enumerables/EmptyIterator.java | Java | apache-2.0 | 326 |
package com.squarespace.template.expr;
import java.util.Arrays;
/**
* Token representing a variable name. Could hold a reference or
* a definition.
*/
public class VarToken extends Token {
public final Object[] name;
public VarToken(Object[] name) {
super(ExprTokenType.VARIABLE);
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VarToken) {
return Arrays.equals(name, ((VarToken)obj).name);
}
return false;
}
@Override
public String toString() {
return "VarToken[" + Arrays.toString(name) + "]";
}
}
| Squarespace/template-compiler | core/src/main/java/com/squarespace/template/expr/VarToken.java | Java | apache-2.0 | 594 |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.jsonoutput;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.commons.vfs.FileObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Converts input rows to one or more XML files.
*
* @author Matt
* @since 14-jan-2006
*/
public class JsonOutput extends BaseStep implements StepInterface
{
private static Class<?> PKG = JsonOutput.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private JsonOutputMeta meta;
private JsonOutputData data;
private interface CompatibilityFactory {
public void execute(Object[] row) throws KettleException;
}
@SuppressWarnings("unchecked")
private class CompatibilityMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
// Create a new object with specified fields
JSONObject jo = new JSONObject();
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
data.ja.add(jo);
}
data.nrRow++;
if(data.nrRowsInBloc>0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
@SuppressWarnings("unchecked")
private class FixedMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
// Create a new object with specified fields
JSONObject jo = new JSONObject();
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
}
data.ja.add(jo);
data.nrRow++;
if(data.nrRowsInBloc > 0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
private CompatibilityFactory compatibilityFactory;
public JsonOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
// Here we decide whether or not to build the structure in
// compatible mode or fixed mode
JsonOutputMeta jsonOutputMeta = (JsonOutputMeta)(stepMeta.getStepMetaInterface());
if (jsonOutputMeta.isCompatibilityMode()) {
compatibilityFactory = new CompatibilityMode();
}
else {
compatibilityFactory = new FixedMode();
}
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
Object[] r = getRow(); // This also waits for a row to be finished.
if (r==null) {
// no more input to be expected...
if(!data.rowsAreSafe) {
// Let's output the remaining unsafe data
outPutRow(r);
}
setOutputDone();
return false;
}
if (first) {
first=false;
data.inputRowMeta=getInputRowMeta();
data.inputRowMetaSize=data.inputRowMeta.size();
if(data.outputValue) {
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
}
// Cache the field name indexes
//
data.nrFields=meta.getOutputFields().length;
data.fieldIndexes = new int[data.nrFields];
for (int i=0;i<data.nrFields;i++) {
data.fieldIndexes[i] = data.inputRowMeta.indexOfValue(meta.getOutputFields()[i].getFieldName());
if (data.fieldIndexes[i]<0) {
throw new KettleException(BaseMessages.getString(PKG, "JsonOutput.Exception.FieldNotFound")); //$NON-NLS-1$
}
JsonOutputField field = meta.getOutputFields()[i];
field.setElementName(environmentSubstitute(field.getElementName()));
}
}
data.rowsAreSafe=false;
compatibilityFactory.execute(r);
if(data.writeToFile && !data.outputValue) {
putRow(data.inputRowMeta,r ); // in case we want it go further...
incrementLinesOutput();
}
return true;
}
@SuppressWarnings("unchecked")
private void outPutRow(Object[] rowData) throws KettleStepException {
// We can now output an object
data.jg = new JSONObject();
data.jg.put(data.realBlocName, data.ja);
String value = data.jg.toJSONString();
if(data.outputValue) {
Object[] outputRowData = RowDataUtil.addValueData(rowData, data.inputRowMetaSize, value);
incrementLinesOutput();
putRow(data.outputRowMeta, outputRowData);
}
if(data.writeToFile) {
// Open a file
if (!openNewFile()) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
}
// Write data to file
try {
data.writer.write(value);
}catch(Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.Writing"), e);
}
// Close file
closeFile();
}
// Data are safe
data.rowsAreSafe=true;
data.ja = new JSONArray();
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(super.init(smi, sdi)) {
data.writeToFile = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_OUTPUT_VALUE);
data.outputValue = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_WRITE_TO_FILE);
if(data.outputValue) {
// We need to have output field name
if(Const.isEmpty(environmentSubstitute(meta.getOutputValue()))) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingOutputFieldName"));
stopAll();
setErrors(1);
return false;
}
}
if(data.writeToFile) {
// We need to have output field name
if(!meta.isServletOutput() && Const.isEmpty(meta.getFileName())) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingTargetFilename"));
stopAll();
setErrors(1);
return false;
}
if(!meta.isDoNotOpenNewFileInit()) {
if (!openNewFile()) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
stopAll();
setErrors(1);
return false;
}
}
}
data.realBlocName = Const.NVL(environmentSubstitute(meta.getJsonBloc()), "");
data.nrRowsInBloc = Const.toInt(environmentSubstitute(meta.getNrRowsInBloc()), 0);
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(data.ja!=null) data.ja=null;
if(data.jg!=null) data.jg=null;
closeFile();
super.dispose(smi, sdi);
}
private void createParentFolder(String filename) throws KettleStepException {
if(!meta.isCreateParentFolder()) return;
// Check for parent folder
FileObject parentfolder=null;
try {
// Get parent folder
parentfolder=KettleVFS.getFileObject(filename, getTransMeta()).getParent();
if(!parentfolder.exists()) {
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName()));
parentfolder.createFolder();
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Log.ParentFolderCreated"));
}
}catch (Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName()));
} finally {
if ( parentfolder != null ){
try {
parentfolder.close();
}catch ( Exception ex ) {};
}
}
}
public boolean openNewFile()
{
if(data.writer!=null) return true;
boolean retval=false;
try {
if (meta.isServletOutput()) {
data.writer = getTrans().getServletPrintWriter();
} else {
String filename = buildFilename();
createParentFolder(filename);
if (meta.AddToResult()) {
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(filename, getTransMeta()), getTransMeta().getName(), getStepname());
resultFile.setComment(BaseMessages.getString(PKG, "JsonOutput.ResultFilenames.Comment"));
addResultFile(resultFile);
}
OutputStream outputStream;
OutputStream fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
outputStream=fos;
if (!Const.isEmpty(meta.getEncoding())) {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000), environmentSubstitute(meta.getEncoding()));
} else {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000));
}
if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JsonOutput.FileOpened", filename));
data.splitnr++;
}
retval=true;
} catch(Exception e) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpeningFile", e.toString()));
}
return retval;
}
public String buildFilename() {
return meta.buildFilename(environmentSubstitute(meta.getFileName()), getCopy(), data.splitnr);
}
private boolean closeFile()
{
if(data.writer==null) return true;
boolean retval=false;
try
{
data.writer.close();
data.writer=null;
retval=true;
}
catch(Exception e)
{
logError(BaseMessages.getString(PKG, "JsonOutput.Error.ClosingFile", e.toString()));
setErrors(1);
retval = false;
}
return retval;
}
} | jjeb/kettle-trunk | engine/src/org/pentaho/di/trans/steps/jsonoutput/JsonOutput.java | Java | apache-2.0 | 14,853 |
define(["Log","FS"],function (Log,FS) {//MODJSL
return function showErrorPos(elem, err) {
var mesg, src, pos;
if (!err) {
close();
return;
}
var row,col;
if (err.isTError) {
mesg=err.mesg;
src=err.src;
pos=err.pos;
row=err.row+1;
col=err.col+1;
} else {
src={name:function (){return "不明";},text:function () {
return null;
}};
pos=0;
mesg=err;
}
function close(){
elem.empty();
}
if(typeof pos=="object") {row=pos.row; col=pos.col;}
close();
var mesgd=$("<div>").text(mesg+" 場所:"+src.name()+(typeof row=="number"?":"+row+":"+col:""));
//mesgd.append($("<button>").text("閉じる").click(close));
elem.append(mesgd);
elem.append($("<div>").attr("class","quickFix"));
console.log("src=",src);
var str=src.text();
if (str && typeof pos=="object") {
var npos=0;
var lines=str.split(/\n/);
for (var i=0 ; i<lines.length && i+1<pos.row ; i++) {
npos+=lines[i].length;
}
npos+=pos.col;
pos=npos;
}
var srcd=$("<pre>");
srcd.append($("<span>").text(str.substring(0,pos)));
srcd.append($("<img>").attr("src",FS.expandPath("${sampleImg}/ecl.png")));//MODJSL
srcd.append($("<span>").text(str.substring(pos)));
elem.append(srcd);
//elem.attr("title",mesg+" 場所:"+src.name());
elem.attr("title","エラー");
var diag=elem.dialog({width:600,height:400});
Log.d("error", mesg+"\nat "+src+":"+err.pos+"\n"+str.substring(0,err.pos)+"##HERE##"+str.substring(err.pos));
return diag;
};
}); | hoge1e3/tonyuedit | war/js/ide/ErrorPos.js | JavaScript | apache-2.0 | 1,670 |
package io.indexr.query.expr.arith;
import com.google.common.collect.Lists;
import java.util.List;
import io.indexr.query.expr.BinaryExpression;
import io.indexr.query.expr.Expression;
import io.indexr.query.types.DataType;
public abstract class BinaryArithmetic extends Expression implements BinaryExpression {
public Expression left, right;
protected DataType dataType;
protected DataType leftType;
protected DataType rightType;
public BinaryArithmetic(Expression left, Expression right) {
this.left = left;
this.right = right;
}
protected DataType defaultType() {
return null;
}
protected void initType() {
if (dataType == null) {
leftType = left.dataType();
rightType = right.dataType();
DataType defaultType = defaultType();
if (defaultType == null) {
dataType = BinaryArithmetic.calType(left.dataType(), right.dataType());
} else {
dataType = defaultType;
}
}
}
@Override
public Expression left() {
return left;
}
@Override
public Expression right() {
return right;
}
@Override
public DataType dataType() {
initType();
return dataType;
}
@Override
public List<Expression> children() {
return Lists.newArrayList(left, right);
}
@Override
public boolean resolved() {
return childrenResolved() && checkInputDataTypes().isSuccess;
}
public static DataType calType(DataType type1, DataType type2) {
return type1.ordinal() >= type2.ordinal() ? type1 : type2;
}
}
| shunfei/indexr | indexr-query-opt/src/main/java/io/indexr/query/expr/arith/BinaryArithmetic.java | Java | apache-2.0 | 1,684 |
package org.ovirt.engine.ui.common.widget.table.column;
import org.ovirt.engine.core.common.businessentities.Disk;
import com.google.gwt.user.cellview.client.Column;
public class DiskStatusColumn extends Column<Disk, Disk> {
public DiskStatusColumn() {
super(new DiskStatusCell());
}
@Override
public Disk getValue(Disk object) {
return object;
}
}
| derekhiggins/ovirt-engine | frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/table/column/DiskStatusColumn.java | Java | apache-2.0 | 391 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.text.tx3g;
import static com.google.common.truth.Truth.assertThat;
import android.graphics.Color;
import android.graphics.Typeface;
import android.test.InstrumentationTestCase;
import android.text.SpannedString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import java.io.IOException;
import java.util.Collections;
/**
* Unit test for {@link Tx3gDecoder}.
*/
public final class Tx3gDecoderTest extends InstrumentationTestCase {
private static final String NO_SUBTITLE = "tx3g/no_subtitle";
private static final String SAMPLE_JUST_TEXT = "tx3g/sample_just_text";
private static final String SAMPLE_WITH_STYL = "tx3g/sample_with_styl";
private static final String SAMPLE_WITH_STYL_ALL_DEFAULTS = "tx3g/sample_with_styl_all_defaults";
private static final String SAMPLE_UTF16_BE_NO_STYL = "tx3g/sample_utf16_be_no_styl";
private static final String SAMPLE_UTF16_LE_NO_STYL = "tx3g/sample_utf16_le_no_styl";
private static final String SAMPLE_WITH_MULTIPLE_STYL = "tx3g/sample_with_multiple_styl";
private static final String SAMPLE_WITH_OTHER_EXTENSION = "tx3g/sample_with_other_extension";
private static final String SAMPLE_WITH_TBOX = "tx3g/sample_with_tbox";
private static final String INITIALIZATION = "tx3g/initialization";
private static final String INITIALIZATION_ALL_DEFAULTS = "tx3g/initialization_all_defaults";
public void testDecodeNoSubtitle() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_SUBTITLE);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertThat(subtitle.getCues(0)).isEmpty();
}
public void testDecodeJustText() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_JUST_TEXT);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStylAllDefaults() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL_ALL_DEFAULTS);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16BeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_BE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16LeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_LE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithMultipleStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_MULTIPLE_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("Line 2\nLine 3");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, 5, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.ITALIC);
findSpan(text, 7, 12, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 5, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
colorSpan = findSpan(text, 7, 12, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithOtherExtension() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_OTHER_EXTENSION);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(2);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testInitializationDecodeWithStyl() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(5);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1f);
}
public void testInitializationDecodeWithTbox() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_TBOX);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1875f);
}
public void testInitializationAllDefaultsDecodeWithStyl() throws IOException,
SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION_ALL_DEFAULTS);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
private static <T> T findSpan(SpannedString testObject, int expectedStart, int expectedEnd,
Class<T> expectedType) {
T[] spans = testObject.getSpans(0, testObject.length(), expectedType);
for (T span : spans) {
if (testObject.getSpanStart(span) == expectedStart
&& testObject.getSpanEnd(span) == expectedEnd) {
return span;
}
}
fail("Span not found.");
return null;
}
private static void assertFractionalLinePosition(Cue cue, float expectedFraction) {
assertThat(cue.lineType).isEqualTo(Cue.LINE_TYPE_FRACTION);
assertThat(cue.lineAnchor).isEqualTo(Cue.ANCHOR_TYPE_START);
assertThat(Math.abs(expectedFraction - cue.line) < 1e-6).isTrue();
}
}
| KiminRyu/ExoPlayer | library/core/src/androidTest/java/com/google/android/exoplayer2/text/tx3g/Tx3gDecoderTest.java | Java | apache-2.0 | 12,407 |
<?php
namespace Spann\Utils;
use Slim\App;
use Slim\Http\Environment;
use Slim\Http\Headers;
use Slim\Http\Request;
use Slim\Http\RequestBody;
use Slim\Http\Response;
use Slim\Http\Uri;
class WebTestClient
{
/** @var \Slim\App */
public $app;
/** @var \Slim\Http\Request */
public $request;
/** @var \Slim\Http\Response */
public $response;
private $cookies = array();
public function __construct(App $slim)
{
$this->app = $slim;
}
public function __call($method, $arguments)
{
throw new \BadMethodCallException(strtoupper($method) . ' is not supported');
}
public function get($path, $data = array(), $optionalHeaders = array())
{
return $this->request('get', $path, $data, $optionalHeaders);
}
public function post($path, $data = array(), $optionalHeaders = array())
{
return $this->request('post', $path, $data, $optionalHeaders);
}
public function patch($path, $data = array(), $optionalHeaders = array())
{
return $this->request('patch', $path, $data, $optionalHeaders);
}
public function put($path, $data = array(), $optionalHeaders = array())
{
return $this->request('put', $path, $data, $optionalHeaders);
}
public function delete($path, $data = array(), $optionalHeaders = array())
{
return $this->request('delete', $path, $data, $optionalHeaders);
}
public function head($path, $data = array(), $optionalHeaders = array())
{
return $this->request('head', $path, $data, $optionalHeaders);
}
public function options($path, $data = array(), $optionalHeaders = array())
{
return $this->request('options', $path, $data, $optionalHeaders);
}
// Abstract way to make a request to SlimPHP, this allows us to mock the
// slim environment
private function request($method, $path, $data = array(), $optionalHeaders = array())
{
//Make method uppercase
$method = strtoupper($method);
$options = array(
'REQUEST_METHOD' => $method,
'REQUEST_URI' => $path
);
if ($method === 'GET') {
$options['QUERY_STRING'] = http_build_query($data);
} else {
$params = json_encode($data);
}
// Prepare a mock environment
$env = Environment::mock(array_merge($options, $optionalHeaders));
$uri = Uri::createFromEnvironment($env);
$headers = Headers::createFromEnvironment($env);
$cookies = $this->cookies;
$serverParams = $env->all();
$body = new RequestBody();
// Attach JSON request
if (isset($params)) {
$headers->set('Content-Type', 'application/json;charset=utf8');
$body->write($params);
}
$this->request = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
$response = new Response();
// Invoke request
$app = $this->app;
$this->response = $app($this->request, $response);
// Return the application output.
return $this->response;
}
public function setCookie($name, $value)
{
$this->cookies[$name] = $value;
}
}
| spann/slim-test-utils | src/Spann/Utils/WebTestClient.php | PHP | apache-2.0 | 3,257 |
"""Support for monitoring OctoPrint sensors."""
from __future__ import annotations
from datetime import datetime, timedelta
import logging
from pyoctoprintapi import OctoprintJobInfo, OctoprintPrinterInfo
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE, TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import OctoprintDataUpdateCoordinator
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
JOB_PRINTING_STATES = ["Printing from SD", "Printing"]
def _is_printer_printing(printer: OctoprintPrinterInfo) -> bool:
return (
printer
and printer.state
and printer.state.flags
and printer.state.flags.printing
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the available OctoPrint binary sensors."""
coordinator: OctoprintDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id
]["coordinator"]
device_id = config_entry.unique_id
assert device_id is not None
entities: list[SensorEntity] = []
if coordinator.data["printer"]:
printer_info = coordinator.data["printer"]
types = ["actual", "target"]
for tool in printer_info.temperatures:
for temp_type in types:
entities.append(
OctoPrintTemperatureSensor(
coordinator,
tool.name,
temp_type,
device_id,
)
)
else:
_LOGGER.error("Printer appears to be offline, skipping temperature sensors")
entities.append(OctoPrintStatusSensor(coordinator, device_id))
entities.append(OctoPrintJobPercentageSensor(coordinator, device_id))
entities.append(OctoPrintEstimatedFinishTimeSensor(coordinator, device_id))
entities.append(OctoPrintStartTimeSensor(coordinator, device_id))
async_add_entities(entities)
class OctoPrintSensorBase(CoordinatorEntity, SensorEntity):
"""Representation of an OctoPrint sensor."""
coordinator: OctoprintDataUpdateCoordinator
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
sensor_type: str,
device_id: str,
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator)
self._device_id = device_id
self._attr_name = f"OctoPrint {sensor_type}"
self._attr_unique_id = f"{sensor_type}-{device_id}"
@property
def device_info(self):
"""Device info."""
return self.coordinator.device_info
class OctoPrintStatusSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_icon = "mdi:printer-3d"
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Current State", device_id)
@property
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
return printer.state.text
@property
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.last_update_success and self.coordinator.data["printer"]
class OctoPrintJobPercentageSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_native_unit_of_measurement = PERCENTAGE
_attr_icon = "mdi:file-percent"
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Job Percentage", device_id)
@property
def native_value(self):
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if not job:
return None
if not (state := job.progress.completion):
return 0
return round(state, 2)
class OctoPrintEstimatedFinishTimeSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_device_class = SensorDeviceClass.TIMESTAMP
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Estimated Finish Time", device_id)
@property
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time_left
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time + timedelta(seconds=job.progress.print_time_left)
class OctoPrintStartTimeSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_device_class = SensorDeviceClass.TIMESTAMP
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Start Time", device_id)
@property
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time - timedelta(seconds=job.progress.print_time)
class OctoPrintTemperatureSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_native_unit_of_measurement = TEMP_CELSIUS
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_state_class = SensorStateClass.MEASUREMENT
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
tool: str,
temp_type: str,
device_id: str,
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, f"{temp_type} {tool} temp", device_id)
self._temp_type = temp_type
self._api_tool = tool
@property
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
for temp in printer.temperatures:
if temp.name == self._api_tool:
val = (
temp.actual_temp
if self._temp_type == "actual"
else temp.target_temp
)
if val is None:
return None
return round(val, 2)
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.last_update_success and self.coordinator.data["printer"]
| home-assistant/home-assistant | homeassistant/components/octoprint/sensor.py | Python | apache-2.0 | 7,576 |
/*
* Copyright 1999-2017 YaoTrue.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yaotrue.web.command;
import java.io.Serializable;
/**
* @author <a href="mailto:yaotrue@163.com">yaotrue</a>
* 2017年8月16日 下午9:15:05
*/
public class BaseCommand implements Serializable {
/**
* <code>{@value}</code>
*/
private static final long serialVersionUID = 6878114738264710696L;
}
| yaotrue/learn-parent | learn-lang/src/main/java/com/yaotrue/web/command/BaseCommand.java | Java | apache-2.0 | 950 |
import jps
import json
import time
class MessageHolder(object):
def __init__(self):
self._saved_msg = []
def __call__(self, msg):
self._saved_msg.append(msg)
def get_msg(self):
return self._saved_msg
def test_multi_pubsub_once():
holder1 = MessageHolder()
holder2 = MessageHolder()
holder3 = MessageHolder()
sub1 = jps.Subscriber('test_utils1', holder1)
sub2 = jps.Subscriber('test_utils2', holder2)
sub3 = jps.Subscriber('test_utils3', holder3)
pub = jps.utils.JsonMultiplePublisher()
time.sleep(0.1)
pub.publish(
'{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}')
time.sleep(0.1)
sub1.spin_once()
sub2.spin_once()
sub3.spin_once()
assert len(holder1.get_msg()) == 1
assert json.loads(holder1.get_msg()[0]) == 'hoge'
assert len(holder2.get_msg()) == 1
obj = json.loads(holder2.get_msg()[0])
assert obj['x'] == 3
assert len(holder3.get_msg()) == 1
assert json.loads(holder3.get_msg()[0]) == 5
def test_to_obj():
msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}'
converted = jps.utils.to_obj(msg)
assert converted.aa == 1
assert converted.bb[0] == 'hoge'
assert converted.bb[1] == 'hogi'
assert len(converted.bb) == 2
assert converted.cc.cc1 == 50
# todo: do
# json = converted.to_json()
# assert json == msg
# todo
def test_to_obj_list():
msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]'
bb = jps.utils.to_obj(msg)
assert len(bb) == 2
assert bb[0] == 'hoge'
assert bb[1] == 'hogi'
assert bb[2].atr1 == 'val2'
assert bb[2].atr2 == 1.0
# json = bb.to_json()
# assert json == msg
def test_to_obj_list():
msg = '[{"hoge": 1}, {"hogi": 2}]'
bb = jps.utils.to_obj(msg)
assert len(bb) == 2
assert bb[0].hoge == 1
assert bb[1].hogi == 2
# todo: list support
# json = bb.to_json()
# assert json == msg
def test_to_obj_simple():
msg = '{"aa": 1, "cc": 3, "bb": 2}'
converted = jps.utils.to_obj(msg)
assert converted.aa == 1
assert converted.bb == 2
assert converted.cc == 3
# works only super simple case
json1 = converted.to_json()
assert json1 == msg
| OTL/jps | test/test_utils.py | Python | apache-2.0 | 2,258 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.j2cache;
public class CacheException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CacheException(String s) {
super(s);
}
public CacheException(String s, Throwable e) {
super(s, e);
}
public CacheException(Throwable e) {
super(e);
}
}
| jior/glaf | workspace/glaf-core/src/main/java/com/glaf/j2cache/CacheException.java | Java | apache-2.0 | 1,115 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.tpch;
import com.facebook.presto.spi.Index;
import com.facebook.presto.spi.RecordSet;
import com.google.common.base.Function;
import static com.facebook.presto.tpch.TpchIndexedData.IndexedTable;
import static com.google.common.base.Preconditions.checkNotNull;
public class TpchIndex
implements Index
{
private final Function<RecordSet, RecordSet> keyFormatter;
private final Function<RecordSet, RecordSet> outputFormatter;
private final IndexedTable indexedTable;
public TpchIndex(Function<RecordSet, RecordSet> keyFormatter, Function<RecordSet, RecordSet> outputFormatter, IndexedTable indexedTable)
{
this.keyFormatter = checkNotNull(keyFormatter, "keyFormatter is null");
this.outputFormatter = checkNotNull(outputFormatter, "outputFormatter is null");
this.indexedTable = checkNotNull(indexedTable, "indexedTable is null");
}
@Override
public RecordSet lookup(RecordSet rawInputRecordSet)
{
// convert the input record set from the column ordering in the query to
// match the column ordering of the index
RecordSet inputRecordSet = keyFormatter.apply(rawInputRecordSet);
// lookup the values in the index
RecordSet rawOutputRecordSet = indexedTable.lookupKeys(inputRecordSet);
// convert the output record set of the index into the column ordering
// expect by the query
return outputFormatter.apply(rawOutputRecordSet);
}
}
| FlxRobin/presto | presto-main/src/test/java/com/facebook/presto/tpch/TpchIndex.java | Java | apache-2.0 | 2,063 |
/*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.pi.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
import org.onosproject.TestApplicationId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.group.DefaultGroup;
import org.onosproject.net.group.DefaultGroupBucket;
import org.onosproject.net.group.DefaultGroupDescription;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.pi.runtime.PiGroupKey;
import org.onosproject.net.pi.runtime.PiMulticastGroupEntry;
import org.onosproject.net.pi.runtime.PiPreReplica;
import java.util.List;
import java.util.Set;
import static org.onosproject.net.group.GroupDescription.Type.ALL;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_SELECTOR;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_TABLE;
/**
* Test for {@link PiMulticastGroupTranslatorImpl}.
*/
public class PiMulticastGroupTranslatorImplTest {
private static final DeviceId DEVICE_ID = DeviceId.deviceId("device:dummy:1");
private static final ApplicationId APP_ID = TestApplicationId.create("dummy");
private static final GroupId GROUP_ID = GroupId.valueOf(1);
private static final PiGroupKey GROUP_KEY = new PiGroupKey(
INGRESS_WCMP_CONTROL_WCMP_TABLE, INGRESS_WCMP_CONTROL_WCMP_SELECTOR, GROUP_ID.id());
private static final List<GroupBucket> BUCKET_LIST = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(3));
private static final List<GroupBucket> BUCKET_LIST_2 = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(2),
allOutputBucket(3),
allOutputBucket(3));
private static final Set<PiPreReplica> REPLICAS = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(3), 1));
private static final Set<PiPreReplica> REPLICAS_2 = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(2), 2),
new PiPreReplica(PortNumber.portNumber(3), 1),
new PiPreReplica(PortNumber.portNumber(3), 2));
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS)
.build();
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP_2 =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS_2)
.build();
private static final GroupBuckets BUCKETS = new GroupBuckets(BUCKET_LIST);
private static final GroupBuckets BUCKETS_2 = new GroupBuckets(BUCKET_LIST_2);
private static final GroupDescription ALL_GROUP_DESC = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC);
private static final GroupDescription ALL_GROUP_DESC_2 = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS_2, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP_2 = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC_2);
private static GroupBucket allOutputBucket(int portNum) {
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(PortNumber.portNumber(portNum))
.build();
return DefaultGroupBucket.createAllGroupBucket(treatment);
}
@Test
public void testTranslatePreGroups() throws Exception {
PiMulticastGroupEntry multicastGroup = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP, null, null);
PiMulticastGroupEntry multicastGroup2 = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP_2, null, null);
new EqualsTester()
.addEqualityGroup(multicastGroup, PI_MULTICAST_GROUP)
.addEqualityGroup(multicastGroup2, PI_MULTICAST_GROUP_2)
.testEquals();
}
}
| kuujo/onos | core/net/src/test/java/org/onosproject/net/pi/impl/PiMulticastGroupTranslatorImplTest.java | Java | apache-2.0 | 5,443 |
package models;
/**
* This class is for boxing the response sent back to slack by the bot.
* @author sabinapokhrel
*/
public class ResponseToClient {
public String status; // Status of the response sent back to slack. It can be either success or fail.
public String message; // The message sent back to the slack by the bot.\
public ResponseToClient(String status, String message) {
this.status = status;
this.message = message;
}
}
| agiledigital/poet-slack-bot | server/app/models/ResponseToClient.java | Java | apache-2.0 | 455 |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2021 Senparc
文件名:RequestMessageEvent_GiftCard_Pay_Done.cs
文件功能描述:用户购买礼品卡付款成功
创建标识:Senparc - 20180906
----------------------------------------------------------------*/
namespace Senparc.Weixin.MP.Entities
{
/// <summary>
/// 用户购买礼品卡付款成功
/// </summary>
public class RequestMessageEvent_GiftCard_Pay_Done : RequestMessageEventBase, IRequestMessageEventBase
{
/// <summary>
/// 事件:用户购买礼品卡付款成功
/// </summary>
public override Event Event
{
get { return Event.giftcard_pay_done; }
}
/// <summary>
/// 货架的id
/// </summary>
public string PageId { get; set; }
/// <summary>
/// 订单号
/// </summary>
public string OrderId { get; set; }
}
}
| mc7246/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/Request/Event/GiftCard/RequestMessageEvent_GiftCard_Pay_Done.cs | C# | apache-2.0 | 1,889 |
// snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_B]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
namespace DynamoDB_intro
{
class Program
{
static void Main(string[] args)
{
// Get an AmazonDynamoDBClient for the local database
AmazonDynamoDBClient client = GetLocalClient();
if (client == null)
{
PauseForDebugWindow();
return;
}
// Create an UpdateItemRequest to modify two existing nested attributes
// and add a new one
UpdateItemRequest updateRequest = new UpdateItemRequest()
{
TableName = "Movies",
Key = new Dictionary<string, AttributeValue>
{
{ "year", new AttributeValue {
N = "2015"
} },
{ "title", new AttributeValue {
S = "The Big New Movie"
}}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":inc", new AttributeValue {
N = "1"
} }
},
UpdateExpression = "SET info.rating = info.rating + :inc",
ReturnValues = "UPDATED_NEW"
};
// Use AmazonDynamoDBClient.UpdateItem to update the specified attributes
UpdateItemResponse uir = null;
try
{
uir = client.UpdateItem(updateRequest);
}
catch (Exception ex)
{
Console.WriteLine("\nError: UpdateItem failed, because " + ex.Message);
if (uir != null)
Console.WriteLine(" Status code was: " + uir.HttpStatusCode.ToString());
PauseForDebugWindow();
return;
}
// Get the item from the table and display it to validate that the update succeeded
DisplayMovieItem(client, "2015", "The Big New Movie");
}
public static AmazonDynamoDBClient GetLocalClient()
{
// First, set up a DynamoDB client for DynamoDB Local
AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
ddbConfig.ServiceURL = "http://localhost:8000";
AmazonDynamoDBClient client;
try
{
client = new AmazonDynamoDBClient(ddbConfig);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
return (null);
}
return (client);
}
public static void DisplayMovieItem(AmazonDynamoDBClient client, string year, string title)
{
// Create Primitives for the HASH and RANGE portions of the primary key
Primitive hash = new Primitive(year, true);
Primitive range = new Primitive(title, false);
Table table = null;
try
{
table = Table.LoadTable(client, "Movies");
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
return;
}
Document document = table.GetItem(hash, range);
Console.WriteLine("\n The movie record looks like this: \n" + document.ToJsonPretty());
}
public static void PauseForDebugWindow()
{
// Keep the console open if in Debug mode...
Console.Write("\n\n ...Press any key to continue");
Console.ReadKey();
Console.WriteLine();
}
}
}
// snippet-end:[dynamodb.dotNET.CodeExample.UpdateItem_B] | awsdocs/aws-doc-sdk-examples | .dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_B/Program.cs | C# | apache-2.0 | 4,866 |
package padroesprojeto.criacional.abstractfactorymethod.outroexemplo.model;
/**
* Created by felansu on 03/06/2015.
*/
public interface Roupa {
void vestir();
}
| felansu/calmanddev | src/main/padroesprojeto/criacional/abstractfactorymethod/outroexemplo/model/Roupa.java | Java | apache-2.0 | 168 |
/**
* Copyright (c) 2011 Jonathan Leibiusky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.navercorp.redis.cluster;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.navercorp.redis.cluster.pipeline.BuilderFactory;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Tuple;
/**
* The Class RedisCluster.
*
* @author jaehong.kim
*/
public class RedisCluster extends BinaryRedisCluster implements
RedisClusterCommands {
/**
* Instantiates a new redis cluster.
*
* @param host the host
*/
public RedisCluster(final String host) {
super(host);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
*/
public RedisCluster(final String host, final int port) {
super(host, port);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
* @param timeout the timeout
*/
public RedisCluster(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Keys
public Long del(final String... keys) {
client.del(keys);
return client.getIntegerReply();
}
public Boolean exists(final String key) {
client.exists(key);
return client.getIntegerReply() == 1;
}
public Long expire(final String key, final int seconds) {
client.expire(key, seconds);
return client.getIntegerReply();
}
public Long expireAt(final String key, final long secondsTimestamp) {
client.expireAt(key, secondsTimestamp);
return client.getIntegerReply();
}
public Long pexpire(final String key, final long milliseconds) {
client.pexpire(key, milliseconds);
return client.getIntegerReply();
}
public Long pexpireAt(final String key, final long millisecondsTimestamp) {
client.pexpireAt(key, millisecondsTimestamp);
return client.getIntegerReply();
}
public Long objectRefcount(String string) {
client.objectRefcount(string);
return client.getIntegerReply();
}
public String objectEncoding(String string) {
client.objectEncoding(string);
return client.getBulkReply();
}
public Long objectIdletime(String string) {
client.objectIdletime(string);
return client.getIntegerReply();
}
public Long ttl(final String key) {
client.ttl(key);
return client.getIntegerReply();
}
public Long pttl(final String key) {
client.pttl(key);
return client.getIntegerReply();
}
public String type(final String key) {
client.type(key);
return client.getStatusCodeReply();
}
public Long persist(final String key) {
client.persist(key);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Strings
public Long append(final String key, final String value) {
client.append(key, value);
return client.getIntegerReply();
}
public Long decr(final String key) {
client.decr(key);
return client.getIntegerReply();
}
public Long decrBy(final String key, final long integer) {
client.decrBy(key, integer);
return client.getIntegerReply();
}
public String get(final String key) {
client.get(key);
return client.getBulkReply();
}
public Boolean getbit(String key, long offset) {
client.getbit(key, offset);
return client.getIntegerReply() == 1;
}
public String getrange(String key, long startOffset, long endOffset) {
client.getrange(key, startOffset, endOffset);
return client.getBulkReply();
}
public String substr(final String key, final int start, final int end) {
client.substr(key, start, end);
return client.getBulkReply();
}
public String getSet(final String key, final String value) {
client.getSet(key, value);
return client.getBulkReply();
}
public Long incr(final String key) {
client.incr(key);
return client.getIntegerReply();
}
public Long incrBy(final String key, final long integer) {
client.incrBy(key, integer);
return client.getIntegerReply();
}
public Double incrByFloat(final String key, final double increment) {
client.incrByFloat(key, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public String set(final String key, String value) {
client.set(key, value);
return client.getStatusCodeReply();
}
public Boolean setbit(String key, long offset, boolean value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
public String setex(final String key, final int seconds, final String value) {
client.setex(key, seconds, value);
return client.getStatusCodeReply();
}
public Long setnx(final String key, final String value) {
client.setnx(key, value);
return client.getIntegerReply();
}
public Long setrange(String key, long offset, String value) {
client.setrange(key, offset, value);
return client.getIntegerReply();
}
public Long strlen(final String key) {
client.strlen(key);
return client.getIntegerReply();
}
public List<String> mget(final String... keys) {
client.mget(keys);
return client.getMultiBulkReply();
}
public String psetex(final String key, final long milliseconds,
final String value) {
client.psetex(key, milliseconds, value);
return client.getStatusCodeReply();
}
public String mset(String... keysvalues) {
client.mset(keysvalues);
return client.getStatusCodeReply();
}
public Long bitcount(final String key) {
client.bitcount(key);
return client.getIntegerReply();
}
public Long bitcount(final String key, long start, long end) {
client.bitcount(key, start, end);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hashes
public Long hdel(final String key, final String... fields) {
client.hdel(key, fields);
return client.getIntegerReply();
}
public Boolean hexists(final String key, final String field) {
client.hexists(key, field);
return client.getIntegerReply() == 1;
}
public String hget(final String key, final String field) {
client.hget(key, field);
return client.getBulkReply();
}
public Map<String, String> hgetAll(final String key) {
client.hgetAll(key);
return BuilderFactory.STRING_MAP
.build(client.getBinaryMultiBulkReply());
}
public Long hincrBy(final String key, final String field, final long value) {
client.hincrBy(key, field, value);
return client.getIntegerReply();
}
public Double hincrByFloat(final String key, final String field,
double increment) {
client.hincrByFloat(key, field, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public Set<String> hkeys(final String key) {
client.hkeys(key);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
public Long hlen(final String key) {
client.hlen(key);
return client.getIntegerReply();
}
public List<String> hmget(final String key, final String... fields) {
client.hmget(key, fields);
return client.getMultiBulkReply();
}
public String hmset(final String key, final Map<String, String> hash) {
client.hmset(key, hash);
return client.getStatusCodeReply();
}
public Long hset(final String key, final String field, final String value) {
client.hset(key, field, value);
return client.getIntegerReply();
}
public Long hsetnx(final String key, final String field, final String value) {
client.hsetnx(key, field, value);
return client.getIntegerReply();
}
public List<String> hvals(final String key) {
client.hvals(key);
final List<String> lresult = client.getMultiBulkReply();
return lresult;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Lists
public String lindex(final String key, final long index) {
client.lindex(key, index);
return client.getBulkReply();
}
public Long linsert(final String key, final LIST_POSITION where,
final String pivot, final String value) {
client.linsert(key, where, pivot, value);
return client.getIntegerReply();
}
public Long llen(final String key) {
client.llen(key);
return client.getIntegerReply();
}
public String lpop(final String key) {
client.lpop(key);
return client.getBulkReply();
}
public Long lpush(final String key, final String... strings) {
client.lpush(key, strings);
return client.getIntegerReply();
}
public Long lpushx(final String key, final String string) {
client.lpushx(key, string);
return client.getIntegerReply();
}
public List<String> lrange(final String key, final long start,
final long end) {
client.lrange(key, start, end);
return client.getMultiBulkReply();
}
public Long lrem(final String key, final long count, final String value) {
client.lrem(key, count, value);
return client.getIntegerReply();
}
public String lset(final String key, final long index, final String value) {
client.lset(key, index, value);
return client.getStatusCodeReply();
}
public String ltrim(final String key, final long start, final long end) {
client.ltrim(key, start, end);
return client.getStatusCodeReply();
}
public String rpop(final String key) {
client.rpop(key);
return client.getBulkReply();
}
public Long rpush(final String key, final String... strings) {
client.rpush(key, strings);
return client.getIntegerReply();
}
public Long rpushx(final String key, final String string) {
client.rpushx(key, string);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sets
public Long sadd(final String key, final String... members) {
client.sadd(key, members);
return client.getIntegerReply();
}
public Long scard(final String key) {
client.scard(key);
return client.getIntegerReply();
}
public Boolean sismember(final String key, final String member) {
client.sismember(key, member);
return client.getIntegerReply() == 1;
}
public Set<String> smembers(final String key) {
client.smembers(key);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
public String srandmember(final String key) {
client.srandmember(key);
return client.getBulkReply();
}
public List<String> srandmember(final String key, final int count) {
client.srandmember(key, count);
return client.getMultiBulkReply();
}
public Long srem(final String key, final String... members) {
client.srem(key, members);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sorted Sets
public Long zadd(final String key, final double score, final String member) {
client.zadd(key, score, member);
return client.getIntegerReply();
}
public Long zadd(final String key, final Map<Double, String> scoreMembers) {
client.zadd(key, scoreMembers);
return client.getIntegerReply();
}
public Long zadd2(final String key, final Map<String, Double> scoreMembers) {
client.zadd2(key, scoreMembers);
return client.getIntegerReply();
}
public Long zcard(final String key) {
client.zcard(key);
return client.getIntegerReply();
}
public Long zcount(final String key, final double min, final double max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Long zcount(final String key, final String min, final String max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Double zincrby(final String key, final double score,
final String member) {
client.zincrby(key, score, member);
String newscore = client.getBulkReply();
return Double.valueOf(newscore);
}
public Set<String> zrange(final String key, final long start, final long end) {
client.zrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<String> zrangeByScore(final String key, final double min,
final double max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final double min,
final double max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrangeWithScores(final String key, final long start,
final long end) {
client.zrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrank(final String key, final String member) {
client.zrank(key, member);
return client.getIntegerReply();
}
public Long zrem(final String key, final String... members) {
client.zrem(key, members);
return client.getIntegerReply();
}
public Long zremrangeByRank(final String key, final long start,
final long end) {
client.zremrangeByRank(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final double start,
final double end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final String start,
final String end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Set<String> zrevrange(final String key, final long start,
final long end) {
client.zrevrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<Tuple> zrevrangeWithScores(final String key, final long start,
final long end) {
client.zrevrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrevrank(final String key, final String member) {
client.zrevrank(key, member);
return client.getIntegerReply();
}
public Double zscore(final String key, final String member) {
client.zscore(key, member);
final String score = client.getBulkReply();
return (score != null ? new Double(score) : null);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Connection
public String ping() {
client.ping();
return client.getStatusCodeReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Server
public String info() {
client.info();
return client.getBulkReply();
}
public String info(final String section) {
client.info(section);
return client.getBulkReply();
}
public Long dbSize() {
client.dbSize();
return client.getIntegerReply();
}
public byte[] dump(final String key) {
client.dump(key);
return client.getBinaryBulkReply();
}
public String restore(final String key, final long ttl,
final byte[] serializedValue) {
client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply();
}
/**
* Quit.
*
* @return the string
*/
public String quit() {
client.quit();
return client.getStatusCodeReply();
}
/**
* Connect.
*/
public void connect() {
client.connect();
}
/**
* Disconnect.
*/
public void disconnect() {
client.disconnect();
}
/**
* Checks if is connected.
*
* @return true, if is connected
*/
public boolean isConnected() {
return client.isConnected();
}
/**
* Gets the tupled set.
*
* @return the tupled set
*/
private Set<Tuple> getTupledSet() {
List<String> membersWithScores = client.getMultiBulkReply();
Set<Tuple> set = new LinkedHashSet<Tuple>();
Iterator<String> iterator = membersWithScores.iterator();
while (iterator.hasNext()) {
set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next())));
}
return set;
}
} | cl9200/nbase-arc | api/java/src/main/java/com/navercorp/redis/cluster/RedisCluster.java | Java | apache-2.0 | 23,864 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.chime.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chime.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetMediaCapturePipelineRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetMediaCapturePipelineRequestProtocolMarshaller implements Marshaller<Request<GetMediaCapturePipelineRequest>, GetMediaCapturePipelineRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/media-capture-pipelines/{mediaPipelineId}").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonChime").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetMediaCapturePipelineRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetMediaCapturePipelineRequest> marshall(GetMediaCapturePipelineRequest getMediaCapturePipelineRequest) {
if (getMediaCapturePipelineRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetMediaCapturePipelineRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, getMediaCapturePipelineRequest);
protocolMarshaller.startMarshalling();
GetMediaCapturePipelineRequestMarshaller.getInstance().marshall(getMediaCapturePipelineRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-chime/src/main/java/com/amazonaws/services/chime/model/transform/GetMediaCapturePipelineRequestProtocolMarshaller.java | Java | apache-2.0 | 2,781 |
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
*
* Xabber 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, see http://www.gnu.org/licenses/.
*/
package com.itracker.android.data.roster;
import android.text.TextUtils;
import com.itracker.android.data.account.StatusMode;
import org.jivesoftware.smack.roster.RosterEntry;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contact in roster.
* <p/>
* {@link #getUser()} always will be bare jid.
*
* @author alexander.ivanov
*/
public class RosterContact extends AbstractContact {
/**
* Contact's name.
*/
protected String name;
/**
* Used groups with its names.
*/
protected final Map<String, RosterGroupReference> groupReferences;
/**
* Whether there is subscription of type "both" or "to".
*/
protected boolean subscribed;
/**
* Whether contact`s account is connected.
*/
protected boolean connected;
/**
* Whether contact`s account is enabled.
*/
protected boolean enabled;
/**
* Data id to view contact information from system contact list.
* <p/>
* Warning: not implemented yet.
*/
private Long viewId;
public RosterContact(String account, RosterEntry rosterEntry) {
this(account, rosterEntry.getUser(), rosterEntry.getName());
}
public RosterContact(String account, String user, String name) {
super(account, user);
if (name == null) {
this.name = null;
} else {
this.name = name.trim();
}
groupReferences = new HashMap<>();
subscribed = true;
connected = true;
enabled = true;
viewId = null;
}
void setName(String name) {
this.name = name;
}
@Override
public Collection<RosterGroupReference> getGroups() {
return Collections.unmodifiableCollection(groupReferences.values());
}
Collection<String> getGroupNames() {
return Collections.unmodifiableCollection(groupReferences.keySet());
}
void addGroupReference(RosterGroupReference groupReference) {
groupReferences.put(groupReference.getName(), groupReference);
}
void setSubscribed(boolean subscribed) {
this.subscribed = subscribed;
}
@Override
public StatusMode getStatusMode() {
return PresenceManager.getInstance().getStatusMode(account, user);
}
@Override
public String getName() {
if (TextUtils.isEmpty(name)) {
return super.getName();
} else {
return name;
}
}
@Override
public boolean isConnected() {
return connected;
}
void setConnected(boolean connected) {
this.connected = connected;
}
public boolean isEnabled() {
return enabled;
}
void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Long getViewId() {
return viewId;
}
}
| bigbugbb/iTracker | app/src/main/java/com/itracker/android/data/roster/RosterContact.java | Java | apache-2.0 | 3,496 |
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/transpose_op.h"
#include <string>
#include <vector>
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
namespace paddle {
namespace operators {
using framework::Tensor;
class TransposeOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null");
auto x_dims = ctx->GetInputDim("X");
std::vector<int> axis = ctx->Attrs().Get<std::vector<int>>("axis");
size_t x_rank = x_dims.size();
size_t axis_size = axis.size();
PADDLE_ENFORCE_EQ(x_rank, axis_size,
"The input tensor's rank(%d) "
"should be equal to the axis's size(%d)",
x_rank, axis_size);
std::vector<int> count(axis_size, 0);
for (size_t i = 0; i < axis_size; i++) {
PADDLE_ENFORCE(
axis[i] < static_cast<int>(axis_size) && ++count[axis[i]] == 1,
"Each element of Attribute axis should be a unique value "
"range from 0 to (dims - 1), "
"where the dims is the axis's size");
}
framework::DDim out_dims(x_dims);
for (size_t i = 0; i < axis_size; i++) {
out_dims[i] = x_dims[axis[i]];
}
ctx->SetOutputDim("Out", out_dims);
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
ctx.GetPlace(), layout_, library_);
}
};
class TransposeOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"X",
"(Tensor) The input tensor, tensors with rank up to 6 are supported.");
AddOutput("Out", "(Tensor)The output tensor.");
AddAttr<std::vector<int>>(
"axis",
"(vector<int>) A list of values, and the size of the list should be "
"the same with the input tensor rank. This operator permutes the input "
"tensor's axes according to the values given.");
AddAttr<bool>("use_mkldnn",
"(bool, default false) Only used in mkldnn kernel")
.SetDefault(false);
AddAttr<std::string>(
"data_format",
"(string, default NCHW) Only used in "
"An optional string from: \"NHWC\", \"NCHW\". "
"Defaults to \"NHWC\". Specify the data format of the output data, "
"the input will be transformed automatically. ")
.SetDefault("AnyLayout");
AddComment(R"DOC(
Transpose Operator.
The input tensor will be permuted according to the axes given.
The behavior of this operator is similar to how `numpy.transpose` works.
- suppose the input `X` is a 2-D tensor:
$$
X = \begin{pmatrix}
0 &1 &2 \\
3 &4 &5
\end{pmatrix}$$
the given `axes` is: $[1, 0]$, and $Y$ = transpose($X$, axis)
then the output $Y$ is:
$$
Y = \begin{pmatrix}
0 &3 \\
1 &4 \\
2 &5
\end{pmatrix}$$
- Given a input tensor with shape $(N, C, H, W)$ and the `axes` is
$[0, 2, 3, 1]$, then shape of the output tensor will be: $(N, H, W, C)$.
)DOC");
}
};
class TransposeOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null");
auto x_dims = ctx->GetInputDim("X");
ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
if (ctx->HasOutput(framework::GradVarName("X"))) {
ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(
ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"))->type(),
ctx.GetPlace(), layout_, library_);
}
};
// FIXME(zcd): transpose2 adds an intermediate output(XShape) based on
// transpose, the XShape is used to carry the shape and lod of X which
// will be used in transpose_grad, in this way, the framework can reuse
// the memory of X immediately the transpose2_op is finished.
// Considering compatibility issues, we could not fix transpose2_op
class Transpose2Op : public TransposeOp {
public:
Transpose2Op(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: TransposeOp(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
TransposeOp::InferShape(ctx);
PADDLE_ENFORCE(ctx->HasOutput("XShape"),
"Output(XShape) should not be null");
const auto &in_dims = ctx->GetInputDim("X");
std::vector<int64_t> x_shape_dim(in_dims.size() + 1);
x_shape_dim[0] = 0;
for (int i = 0; i < in_dims.size(); ++i) {
x_shape_dim[i + 1] = in_dims[i];
}
ctx->SetOutputDim("XShape", framework::make_ddim(x_shape_dim));
ctx->ShareLoD("X", /*->*/ "XShape");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
ctx.GetPlace(), layout_, library_);
}
};
class Transpose2OpMaker : public TransposeOpMaker {
public:
void Make() override {
TransposeOpMaker::Make();
AddOutput("XShape", "(Tensor)The output tensor.").AsIntermediate();
}
};
class Transpose2GradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
std::unique_ptr<framework::OpDesc> Apply() const override {
auto *grad_op = new framework::OpDesc();
grad_op->SetType("transpose2_grad");
grad_op->SetInput("XShape", Output("XShape"));
grad_op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
grad_op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
grad_op->SetAttrMap(Attrs());
return std::unique_ptr<framework::OpDesc>(grad_op);
}
};
class Transpose2OpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("XShape"), "Input(XShape) should not be null");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null");
if (ctx->HasOutput(framework::GradVarName("X"))) {
auto xshape_dim = ctx->GetInputDim("XShape");
auto x_shape_dim =
framework::slice_ddim(xshape_dim, 1, xshape_dim.size());
ctx->SetOutputDim(framework::GradVarName("X"), x_shape_dim);
ctx->ShareLoD("XShape", framework::GradVarName("X"));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(
ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"))->type(),
ctx.GetPlace(), layout_, library_);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(transpose, ops::TransposeOp, ops::TransposeOpMaker,
paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(transpose_grad, ops::TransposeOpGrad);
REGISTER_OP_CPU_KERNEL(
transpose, ops::TransposeKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
transpose_grad,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OPERATOR(transpose2, ops::Transpose2Op, ops::Transpose2OpMaker,
ops::Transpose2GradMaker);
REGISTER_OPERATOR(transpose2_grad, ops::Transpose2OpGrad);
REGISTER_OP_CPU_KERNEL(
transpose2, ops::TransposeKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
transpose2_grad,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, double>);
| baidu/Paddle | paddle/fluid/operators/transpose_op.cc | C++ | apache-2.0 | 11,179 |
#region License Header
/*
* QUANTLER.COM - Quant Fund Development Platform
* Quantler Core Trading Engine. Copyright 2018 Quantler B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion License Header
using Quantler.Exchanges;
using System;
using System.Linq;
namespace Quantler.Scheduler
{
/// <summary>
/// Date composition
/// </summary>
/// <seealso cref="DateComposite" />
public class DateFunc : DateComposite
{
#region Private Fields
/// <summary>
/// The next date function
/// </summary>
private readonly Func<DateTime, DateTime> _nextDateFunc;
/// <summary>
/// The previous date, in case we need to remember this
/// </summary>
private DateTime _previousDate = DateTime.MinValue;
#endregion Private Fields
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DateFunc"/> class.
/// </summary>
public DateFunc()
{
}
#endregion Public Constructors
#region Private Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DateFunc"/> class.
/// </summary>
/// <param name="nextdatefunc">The next date function.</param>
/// <param name="name"></param>
private DateFunc(Func<DateTime, DateTime> nextdatefunc, string name)
{
_nextDateFunc = nextdatefunc;
Name = name;
}
#endregion Private Constructors
#region Public Properties
/// <summary>
/// Name of the composite, for easier logging
/// </summary>
public string Name { get; }
#endregion Public Properties
#region Public Methods
/// <summary>
/// Last trading day of each month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite EndOfMonth(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Derive the next date
var derived = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone).AddMonths(2).DoWhile(n => n.AddDays(-1),
i => !exchangeModel.IsOpenOnDate(i) && x.Month != i.Month + 1);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "End-Of-Every-Month");
/// <summary>
/// Last trading day of specified month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <param name="month">The month.</param>
/// <returns></returns>
public DateComposite EndOfMonth(ExchangeModel exchangeModel, int month) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(
x.Month > month || (!exchangeModel.IsOpenOnDate(x) && x.Month == month) ? x.Year + 1 : x.Year,
12, 31)
.DoWhile(n => n.AddDays(-1), i => !exchangeModel.IsOpenOnDate(i) && i.Month != month);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, $"End-Of-Month-{month}");
/// <summary>
/// Last trading day of each week
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite EndOfWeek(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = x.AddDays(7 - ((int) x.DayOfWeek + 1 > 0 ? (int) x.DayOfWeek + 2 : 0))
.DoWhile(n => n.AddDays(-1), n => !exchangeModel.IsOpenOnDate(n));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "End-Of-Week");
/// <summary>
/// Every day.
/// </summary>
/// <returns></returns>
public DateComposite EveryDay() =>
new DateFunc(x =>
{
//Set previous date
if (_previousDate.Date != x.Date)
{
_previousDate = x.Date.AddDays(1);
return _previousDate;
}
else
return x;
}, "Every-Day");
/// <summary>
/// Every day.
/// </summary>
/// <returns></returns>
public DateComposite EveryTradingDay(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Set previous date
var derived = x;
if (_previousDate.Date != x.Date)
{
_previousDate = _previousDate.DoWhile(n => n.AddDays(1), n => !exchangeModel.IsOpenOnDate(n));
derived = _previousDate;
}
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Every-TradingDay");
/// <summary>
/// Get the next date and time to execute this event
/// </summary>
/// <param name="dateutc">Current date in utc.</param>
/// <returns></returns>
public DateTime NextDate(DateTime dateutc) =>
_nextDateFunc(dateutc);
/// <summary>
/// On a specific year, month and day
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month.</param>
/// <param name="day">The day.</param>
/// <returns></returns>
public DateComposite On(int year, int month, int day) =>
new DateFunc(x => new DateTime(year, month, day), $"At-Date-{year}-{month}-{day}");
/// <summary>
/// On specified days
/// </summary>
/// <param name="dates">The dates.</param>
/// <returns></returns>
public DateComposite On(params DateTime[] dates) =>
new DateFunc(x => x.DoWhile(n => n.AddDays(1), n => dates.Count(i => i.Day == n.Day && i.Month == n.Month) == 0), $"On-Dates-{string.Join("-", dates)}");
/// <summary>
/// On the specified days of the week
/// </summary>
/// <param name="days">The days.</param>
/// <returns></returns>
public DateComposite On(params DayOfWeek[] days) =>
new DateFunc(x => x.DoWhile(n => n.AddDays(1), n => !days.Contains(n.DayOfWeek)), $"On-Day-Of-Week-{string.Join("-", days)}");
/// <summary>
/// On the first trading day of the month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite StartOfMonth(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(x.Year, x.Month, 1).AddMonths(1)
.DoWhile(n => n.AddDays(1), i => !exchangeModel.IsOpenOnDate(i));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Start-Of-Every-Month");
/// <summary>
/// On the first trading day of the specified month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <param name="month">The month.</param>
/// <returns></returns>
public DateComposite StartOfMonth(ExchangeModel exchangeModel, int month) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(x.Month >= month ? x.Year + 1 : x.Year, 1, 1)
.DoWhile(n => n.AddDays(1), i => !exchangeModel.IsOpenOnDate(i) && i.Month != month);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, $"Start-Of-{month}-Month");
/// <summary>
/// On the first trading day of the week
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite StartOfWeek(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = x.AddDays(7).AddDays(DayOfWeek.Monday - x.DayOfWeek)
.DoWhile(n => n.AddDays(1), n => !exchangeModel.IsOpenOnDate(n));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Start-Of-Every-Week");
#endregion Public Methods
}
} | Quantler/Core | Quantler/Scheduler/DateFunc.cs | C# | apache-2.0 | 10,177 |
/*
* Copyright 2011-2015 The Trustees of the University of Pennsylvania
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.upenn.library.xmlaminar.parallel;
import static edu.upenn.library.xmlaminar.parallel.JoiningXMLFilter.GROUP_BY_SYSTEMID_FEATURE_NAME;
import edu.upenn.library.xmlaminar.parallel.callback.OutputCallback;
import edu.upenn.library.xmlaminar.parallel.callback.StdoutCallback;
import edu.upenn.library.xmlaminar.parallel.callback.XMLReaderCallback;
import edu.upenn.library.xmlaminar.VolatileSAXSource;
import edu.upenn.library.xmlaminar.VolatileXMLFilterImpl;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import javax.xml.transform.sax.SAXSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.XMLFilterImpl;
/**
*
* @author Michael Gibney
*/
public class SplittingXMLFilter extends QueueSourceXMLFilter implements OutputCallback {
private static final Logger LOG = LoggerFactory.getLogger(SplittingXMLFilter.class);
private final AtomicBoolean parsing = new AtomicBoolean(false);
private volatile Future<?> consumerTask;
private int level = -1;
private int startEventLevel = -1;
private final ArrayDeque<StructuralStartEvent> startEventStack = new ArrayDeque<StructuralStartEvent>();
public static void main(String[] args) throws Exception {
LevelSplittingXMLFilter sxf = new LevelSplittingXMLFilter();
sxf.setChunkSize(1);
sxf.setOutputCallback(new StdoutCallback());
sxf.setInputType(InputType.indirect);
sxf.parse(new InputSource("../cli/whole-indirect.txt"));
}
public void ensureCleanInitialState() {
if (level != -1) {
throw new IllegalStateException("level != -1: "+level);
}
if (startEventLevel != -1) {
throw new IllegalStateException("startEventLevel != -1: "+startEventLevel);
}
if (!startEventStack.isEmpty()) {
throw new IllegalStateException("startEventStack not empty: "+startEventStack.size());
}
if (parsing.get()) {
throw new IllegalStateException("already parsing");
}
if (consumerTask != null) {
throw new IllegalStateException("consumerTask not null");
}
if (producerThrowable != null || consumerThrowable != null) {
throw new IllegalStateException("throwable not null: "+producerThrowable+", "+consumerThrowable);
}
int arrived;
if ((arrived = parseBeginPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseBeginPhaser arrived count: "+arrived);
}
if ((arrived = parseEndPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseEndPhaser arrived count: "+arrived);
}
if ((arrived = parseChunkDonePhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseChunkDonePhaser arrived count: "+arrived);
}
}
@Override
protected void initialParse(VolatileSAXSource in) {
synchronousParser.setParent(this);
setupParse(in.getInputSource());
}
@Override
protected void repeatParse(VolatileSAXSource in) {
reset(false);
setupParse(in.getInputSource());
}
private void setupParse(InputSource in) {
setContentHandler(synchronousParser);
if (!parsing.compareAndSet(false, true)) {
throw new IllegalStateException("failed setting parsing = true");
}
OutputLooper outputLoop = new OutputLooper(in, null, Thread.currentThread());
consumerTask = getExecutor().submit(outputLoop);
}
@Override
protected void finished() throws SAXException {
reset(false);
}
public void reset() {
try {
setFeature(RESET_PROPERTY_NAME, true);
} catch (SAXException ex) {
throw new AssertionError(ex);
}
}
protected void reset(boolean cancel) {
try {
if (consumerTask != null) {
if (cancel) {
consumerTask.cancel(true);
} else {
consumerTask.get();
}
}
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
consumerTask = null;
consumerThrowable = null;
producerThrowable = null;
if (splitDirector != null) {
splitDirector.reset();
}
startEventStack.clear();
if (!parsing.compareAndSet(false, false) && !cancel) {
LOG.warn("at {}.reset(), parsing had been set to true", SplittingXMLFilter.class.getName(), new IllegalStateException());
}
}
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name) && value) {
try {
super.setFeature(name, value);
} catch (SAXException ex) {
/*
* could run here if only want to run if deepest resettable parent.
* ... but I don't think that's the case here.
*/
}
/*
* reset(false) because the downstream consumer thread issued this
* reset request (initiated the interruption).
*/
reset(true);
} else {
super.setFeature(name, value);
}
}
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name)) {
try {
return super.getFeature(name) && consumerTask == null;
} catch (SAXException ex) {
return consumerTask == null;
}
} else if (GROUP_BY_SYSTEMID_FEATURE_NAME.equals(name)) {
return false;
}else {
return super.getFeature(name);
}
}
private final SynchronousParser synchronousParser = new SynchronousParser();
@Override
public boolean allowOutputCallback() {
return true;
}
private class SynchronousParser extends VolatileXMLFilterImpl {
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse();
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse();
}
private void parse() throws SAXException, IOException {
parseBeginPhaser.arrive();
try {
parseEndPhaser.awaitAdvanceInterruptibly(parseEndPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
parseChunkDonePhaser.arrive();
}
}
private final Phaser parseBeginPhaser = new Phaser(2);
private final Phaser parseEndPhaser = new Phaser(2);
private final Phaser parseChunkDonePhaser = new Phaser(2);
private class OutputLooper implements Runnable {
private final InputSource input;
private final String systemId;
private final Thread producer;
private OutputLooper(InputSource in, String systemId, Thread producer) {
this.input = in;
this.systemId = systemId;
this.producer = producer;
}
private void parseLoop(InputSource input, String systemId) throws SAXException, IOException {
if (input != null) {
while (parsing.get()) {
outputCallback.callback(new VolatileSAXSource(synchronousParser, input));
try {
parseChunkDonePhaser.awaitAdvanceInterruptibly(parseChunkDonePhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
} else {
throw new NullPointerException("null InputSource");
}
}
@Override
public void run() {
try {
parseLoop(input, systemId);
} catch (Throwable t) {
if (producerThrowable == null) {
consumerThrowable = t;
producer.interrupt();
} else {
t = producerThrowable;
producerThrowable = null;
throw new RuntimeException(t);
}
}
}
}
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse(input, null);
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse(null, systemId);
}
private void parse(InputSource input, String systemId) {
try {
if (input != null) {
super.parse(input);
} else {
super.parse(systemId);
}
} catch (Throwable t) {
try {
if (consumerThrowable == null) {
producerThrowable = t;
reset(true);
} else {
t = consumerThrowable;
consumerThrowable = null;
}
} finally {
if (outputCallback != null) {
outputCallback.finished(t);
}
throw new RuntimeException(t);
}
}
outputCallback.finished(null);
}
@Override
public XMLReaderCallback getOutputCallback() {
return outputCallback;
}
@Override
public void setOutputCallback(XMLReaderCallback xmlReaderCallback) {
this.outputCallback = xmlReaderCallback;
}
private volatile XMLReaderCallback outputCallback;
private volatile Throwable consumerThrowable;
private volatile Throwable producerThrowable;
@Override
public void startDocument() throws SAXException {
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
startEventStack.push(new StructuralStartEvent());
super.startDocument();
level++;
startEventLevel++;
}
@Override
public void endDocument() throws SAXException {
startEventLevel--;
level--;
super.endDocument();
startEventStack.pop();
if (!parsing.compareAndSet(true, false)) {
throw new IllegalStateException("failed at endDocument setting parsing = false");
}
parseEndPhaser.arrive();
}
private int bypassLevel = Integer.MAX_VALUE;
private int bypassStartEventLevel = Integer.MAX_VALUE;
protected final void split() throws SAXException {
writeSyntheticEndEvents();
parseEndPhaser.arrive();
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
writeSyntheticStartEvents();
}
private void writeSyntheticEndEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.iterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.endDocument();
break;
case PREFIX_MAPPING:
super.endPrefixMapping(next.one);
break;
case ELEMENT:
super.endElement(next.one, next.two, next.three);
}
}
}
private void writeSyntheticStartEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.descendingIterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.startDocument();
break;
case PREFIX_MAPPING:
super.startPrefixMapping(next.one, next.two);
break;
case ELEMENT:
super.startElement(next.one, next.two, next.three, next.atts);
}
}
}
private SplitDirector splitDirector = new SplitDirector();
public SplitDirector getSplitDirector() {
return splitDirector;
}
public void setSplitDirector(SplitDirector splitDirector) {
this.splitDirector = splitDirector;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startElement(uri, localName, qName, atts, level))) {
startEventStack.push(new StructuralStartEvent(uri, localName, qName, atts));
}
super.startElement(uri, localName, qName, atts);
level++;
startEventLevel++;
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startPrefixMapping(prefix, uri, level))) {
startEventStack.push(new StructuralStartEvent(prefix, uri));
}
super.startPrefixMapping(prefix, uri);
startEventLevel++;
}
/**
* Returns true if the generating event should be added to
* the startEvent stack
* @param directive
* @return
* @throws SAXException
*/
private boolean handleDirective(SplitDirective directive) throws SAXException {
switch (directive) {
case SPLIT:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
split();
return false;
case SPLIT_NO_BYPASS:
split();
return true;
case NO_SPLIT_BYPASS:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
return false;
case NO_SPLIT:
return true;
default:
throw new AssertionError();
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
startEventLevel--;
level--;
super.endElement(uri, localName, qName);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endElement(uri, localName, qName, level));
}
}
private boolean handleStructuralEndEvent() {
if (level > bypassLevel) {
return false;
} else if (level < bypassLevel) {
startEventStack.pop();
return true;
} else {
if (startEventLevel == bypassStartEventLevel) {
bypassEnd();
return true;
} else if (startEventLevel < bypassStartEventLevel) {
startEventStack.pop();
return true;
} else {
return false;
}
}
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
startEventLevel--;
super.endPrefixMapping(prefix);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endPrefixMapping(prefix, level));
}
}
private void bypassEnd() {
bypassLevel = Integer.MAX_VALUE;
bypassStartEventLevel = Integer.MAX_VALUE;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.characters(ch, start, length, level));
}
super.characters(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.ignorableWhitespace(ch, start, length, level));
}
super.ignorableWhitespace(ch, start, length);
}
@Override
public void skippedEntity(String name) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.skippedEntity(name, level));
}
super.skippedEntity(name);
}
public static enum SplitDirective { SPLIT, NO_SPLIT, SPLIT_NO_BYPASS, NO_SPLIT_BYPASS }
public static class SplitDirector {
public void reset() {
// default NOOP implementation
}
public SplitDirective startPrefixMapping(String prefix, String uri, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endPrefixMapping(String prefix, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective startElement(String uri, String localName, String qName, Attributes atts, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endElement(String uri, String localName, String qName, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective characters(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective ignorableWhitespace(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective skippedEntity(String name, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
}
}
| upenn-libraries/xmlaminar | parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/SplittingXMLFilter.java | Java | apache-2.0 | 19,266 |
// <copyright file="BatchModeBuffer.cs" company="ClrCoder project">
// Copyright (c) ClrCoder project. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// </copyright>
#if !NETSTANDARD1_0 && !NETSTANDARD1_1
namespace ClrCoder.Threading.Channels
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
/// <summary>
/// TODO: Implement and test me.
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class BatchModeBuffer<T> : IDataFlowConsumer<T>, IDataFlowProducer<T>
{
private static readonly T[] EmptyBuffer = new T[0];
[CanBeNull]
private readonly object _syncRoot;
private readonly int _maxBufferLength;
private readonly int _minReadSize;
private readonly TimeSpan _maxReadAccumulationDelay;
private readonly Dictionary<int, LinkedListNode<SliceEntry>> _idToSliceEntries =
new Dictionary<int, LinkedListNode<SliceEntry>>();
private readonly LinkedList<SliceEntry> _sliceEntries = new LinkedList<SliceEntry>();
private readonly int _maxSliceLength;
private int _nextId = 0;
/// <summary>
/// </summary>
/// <param name="maxBufferLength"></param>
/// <param name="minReadSize"></param>
public BatchModeBuffer(
int maxBufferLength,
int minReadSize,
TimeSpan maxReadAccumulationDelay,
object syncRoot = null)
{
_maxBufferLength = maxBufferLength;
_minReadSize = minReadSize;
_maxReadAccumulationDelay = maxReadAccumulationDelay;
_syncRoot = syncRoot;
_maxSliceLength = Math.Max(512, _minReadSize);
}
private enum SliceEntryStatus
{
AllocatedForWrite,
Data,
AllocatedForRead
}
/// <inheritdoc/>
public IChannelReader<T> OpenReader()
{
throw new NotImplementedException();
}
/// <inheritdoc/>
public IChannelWriter<T> OpenWriter()
{
if (_syncRoot == null)
{
return new BatchModeBufferWriter<SyncFreeObject>(this, default);
}
return new BatchModeBufferWriter<MonitorSyncObject>(this, new MonitorSyncObject(_syncRoot));
}
private SliceEntry AllocateEmptyEntryAfter(LinkedListNode<SliceEntry> node)
{
var newEntry = new SliceEntry
{
Id = _nextId++
};
_sliceEntries.AddAfter(node, newEntry);
return newEntry;
}
private SliceEntry AllocateNewEntry()
{
var result = new SliceEntry
{
Buffer = new T[_maxSliceLength],
Status = SliceEntryStatus.Data,
Id = _nextId++
};
_idToSliceEntries.Add(result.Id, _sliceEntries.AddLast(result));
return result;
}
private void RemoveNode(LinkedListNode<SliceEntry> sliceEntryNode)
{
_idToSliceEntries.Remove(sliceEntryNode.Value.Id);
_sliceEntries.Remove(sliceEntryNode);
}
private Span<T> TryAllocateUnsafe(int amount)
{
// We don't check logical amount.
SliceEntry lastEntry = _sliceEntries.Last?.Value;
Span<T> result;
if ((lastEntry != null)
&& (lastEntry.Status == SliceEntryStatus.Data))
{
result = lastEntry.AllocateForWrite(amount);
if (result.Length != 0)
{
return result;
}
}
lastEntry = AllocateNewEntry();
return lastEntry.AllocateForWrite(amount);
}
private class SliceEntry
{
public int Id;
public T[] Buffer;
public int Start;
public int Length;
public SliceEntryStatus Status;
public int SpaceLeft => Buffer.Length - Start - Length;
public Span<T> AllocateForWrite(int maxAmount)
{
int writePosition = Start + Length;
int amount = Math.Min(Buffer.Length - writePosition, maxAmount);
Length += amount;
return new Span<T>(Buffer, writePosition, amount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryWriteLast(T item)
{
bool result = false;
int writePosition = Start + Length;
if (writePosition < Buffer.Length)
{
Buffer[writePosition] = item;
Length++;
result = true;
}
return result;
}
}
}
}
#endif | dmitriyse/ClrCoder | src/ClrCoder/Threading/Channels/BatchModeBuffer/BatchModeBuffer.cs | C# | apache-2.0 | 5,205 |
package bamboo.crawl;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class RecordStats {
private static final Date MAX_TIME = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(900));
private static final Date MIN_TIME = new Date(631152000000L);
private long records;
private long recordBytes;
private Date startTime = null;
private Date endTime = null;
public void update(long recordLength, Date time) {
records += 1;
recordBytes += recordLength;
if (time.after(MIN_TIME) && time.before(MAX_TIME)) {
if (startTime == null || time.before(startTime)) {
startTime = time;
}
if (endTime == null || time.after(endTime)) {
endTime = time;
}
}
}
public long getRecords() {
return records;
}
public long getRecordBytes() {
return recordBytes;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
@Override
public String toString() {
return "RecordStats{" +
"records=" + records +
", recordBytes=" + recordBytes +
", startTime=" + startTime +
", endTime=" + endTime +
'}';
}
}
| nla/bamboo | ui/src/bamboo/crawl/RecordStats.java | Java | apache-2.0 | 1,362 |
package com.example.nm_gql_go_link_example;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}
| google/note-maps | flutter/nm_gql_go_link/example/android/app/src/main/java/com/example/nm_gql_go_link_example/MainActivity.java | Java | apache-2.0 | 153 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
'use strict';
var module = angular.module('pnc.common.restclient', [
'ngResource',
'pnc.common.util',
]);
// TODO: Remove this unnecessary layer of indirection.
module.factory('REST_BASE_URL', [
'restConfig',
function(restConfig) {
return restConfig.getPncUrl();
}
]);
module.factory('REST_BASE_REST_URL', [
'restConfig',
function(restConfig) {
return restConfig.getPncRestUrl();
}
]);
})();
| matedo1/pnc | ui/app/common/restclient/restclient.module.js | JavaScript | apache-2.0 | 1,179 |
/*
* 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.hyracks.storage.am.lsm.invertedindex.util;
import java.util.List;
import org.apache.hyracks.api.comm.IFrameTupleAccessor;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.ErrorCode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilterFactory;
import org.apache.hyracks.storage.am.btree.frames.BTreeLeafFrameType;
import org.apache.hyracks.storage.am.btree.frames.BTreeNSMInteriorFrameFactory;
import org.apache.hyracks.storage.am.btree.tuples.BTreeTypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.btree.util.BTreeUtils;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.IPageManager;
import org.apache.hyracks.storage.am.common.api.IPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMPageWriteCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCache;
import org.apache.hyracks.storage.am.lsm.common.frames.LSMComponentFilterFrameFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.BTreeFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.ComponentFilterHelper;
import org.apache.hyracks.storage.am.lsm.common.impls.LSMComponentFilterManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.fulltext.IFullTextConfigEvaluatorFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexFileManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.PartitionedLSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.InMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.PartitionedInMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.InvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeElementInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory;
import org.apache.hyracks.storage.common.buffercache.IBufferCache;
import org.apache.hyracks.util.trace.ITracer;
public class InvertedIndexUtils {
public static final String EXPECT_ALL_FIX_GET_VAR_SIZE =
"expecting all type traits to be fixed-size while getting at least one variable-length one";
public static final String EXPECT_VAR_GET_ALL_FIX_SIZE =
"expecting at least one variable-size type trait while all are fixed-size";
public static InMemoryInvertedIndex createInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new InMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, tokenizerFactory, fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static InMemoryInvertedIndex createPartitionedInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new PartitionedInMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static OnDiskInvertedIndex createOnDiskInvertedIndex(IIOManager ioManager, IBufferCache bufferCache,
ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new OnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static PartitionedOnDiskInvertedIndex createPartitionedOnDiskInvertedIndex(IIOManager ioManager,
IBufferCache bufferCache, ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new PartitionedOnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static FileReference getBTreeFile(IIOManager ioManager, FileReference invListsFile)
throws HyracksDataException {
return ioManager.resolveAbsolutePath(invListsFile.getFile().getPath() + "_btree");
}
public static BTreeFactory createDeletedKeysBTreeFactory(IIOManager ioManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, IBufferCache diskBufferCache,
IPageManagerFactory freePageManagerFactory) throws HyracksDataException {
BTreeTypeAwareTupleWriterFactory tupleWriterFactory =
new BTreeTypeAwareTupleWriterFactory(invListTypeTraits, false);
ITreeIndexFrameFactory leafFrameFactory =
BTreeUtils.getLeafFrameFactory(tupleWriterFactory, BTreeLeafFrameType.REGULAR_NSM);
ITreeIndexFrameFactory interiorFrameFactory = new BTreeNSMInteriorFrameFactory(tupleWriterFactory);
return new BTreeFactory(ioManager, diskBufferCache, freePageManagerFactory, interiorFrameFactory,
leafFrameFactory, invListCmpFactories, invListCmpFactories.length);
}
public static LSMInvertedIndex createLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IMetadataPageManagerFactory pageManagerFactory, ITracer tracer)
throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
OnDiskInvertedIndexFactory invIndexFactory =
new OnDiskInvertedIndexFactory(ioManager, diskBufferCache, invListBuilderFactory, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new LSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper, filterFrameFactory,
filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static PartitionedLSMInvertedIndex createPartitionedLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IPageManagerFactory pageManagerFactory, ITracer tracer) throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
PartitionedOnDiskInvertedIndexFactory invIndexFactory = new PartitionedOnDiskInvertedIndexFactory(ioManager,
diskBufferCache, invListBuilderFactory, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new PartitionedLSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper,
filterFrameFactory, filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager,
invListTypeTraits, invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static boolean checkTypeTraitsAllFixed(ITypeTraits[] typeTraits) {
for (int i = 0; i < typeTraits.length; i++) {
if (!typeTraits[i].isFixedLength()) {
return false;
}
}
return true;
}
public static void verifyAllFixedSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == false) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_ALL_FIX_GET_VAR_SIZE);
}
}
public static void verifyHasVarSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == true) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_VAR_GET_ALL_FIX_SIZE);
}
}
public static IInvertedListTupleReference createInvertedListTupleReference(ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListTupleReference(typeTraits);
} else {
return new VariableSizeInvertedListTupleReference(typeTraits);
}
}
public static IFrameTupleAccessor createInvertedListFrameTupleAccessor(int frameSize, ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
} else {
return new VariableSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
}
}
public static void setInvertedListFrameEndOffset(byte[] bytes, int pos) {
int off = bytes.length - 4;
bytes[off++] = (byte) (pos >> 24);
bytes[off++] = (byte) (pos >> 16);
bytes[off++] = (byte) (pos >> 8);
bytes[off] = (byte) (pos);
}
public static int getInvertedListFrameEndOffset(byte[] bytes) {
int p = bytes.length - 4;
int offsetFrameEnd = 0;
for (int i = 0; i < 4; i++) {
offsetFrameEnd = (offsetFrameEnd << 8) + (bytes[p++] & 0xFF);
}
return offsetFrameEnd;
}
}
| apache/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-invertedindex/src/main/java/org/apache/hyracks/storage/am/lsm/invertedindex/util/InvertedIndexUtils.java | Java | apache-2.0 | 19,511 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*
* @file
*/
#include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_interface.h"
#include <algorithm>
#include "cyber/common/log.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
DualVariableWarmStartSlackOSQPInterface::
DualVariableWarmStartSlackOSQPInterface(
size_t horizon, double ts, const Eigen::MatrixXd& ego,
const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num,
const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b,
const Eigen::MatrixXd& xWS,
const PlannerOpenSpaceConfig& planner_open_space_config)
: ts_(ts),
ego_(ego),
obstacles_edges_num_(obstacles_edges_num),
obstacles_A_(obstacles_A),
obstacles_b_(obstacles_b),
xWS_(xWS) {
ACHECK(horizon < std::numeric_limits<int>::max())
<< "Invalid cast on horizon in open space planner";
horizon_ = static_cast<int>(horizon);
ACHECK(obstacles_num < std::numeric_limits<int>::max())
<< "Invalid cast on obstacles_num in open space planner";
obstacles_num_ = static_cast<int>(obstacles_num);
w_ev_ = ego_(1, 0) + ego_(3, 0);
l_ev_ = ego_(0, 0) + ego_(2, 0);
g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2};
offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0);
obstacles_edges_sum_ = obstacles_edges_num_.sum();
l_start_index_ = 0;
n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1);
s_start_index_ = n_start_index_ + 4 * obstacles_num_ * (horizon_ + 1);
l_warm_up_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1);
n_warm_up_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1);
slacks_ = Eigen::MatrixXd::Zero(obstacles_num_, horizon_ + 1);
// get_nlp_info
lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1);
miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1);
slack_horizon_ = obstacles_num_ * (horizon_ + 1);
// number of variables
num_of_variables_ = lambda_horizon_ + miu_horizon_ + slack_horizon_;
// number of constraints
num_of_constraints_ = 3 * obstacles_num_ * (horizon_ + 1) + num_of_variables_;
min_safety_distance_ =
planner_open_space_config.dual_variable_warm_start_config()
.min_safety_distance();
check_mode_ =
planner_open_space_config.dual_variable_warm_start_config().debug_osqp();
beta_ = planner_open_space_config.dual_variable_warm_start_config().beta();
osqp_config_ =
planner_open_space_config.dual_variable_warm_start_config().osqp_config();
}
void DualVariableWarmStartSlackOSQPInterface::printMatrix(
const int r, const int c, const std::vector<c_float>& P_data,
const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) {
Eigen::MatrixXf tmp = Eigen::MatrixXf::Zero(r, c);
for (size_t i = 0; i < P_indptr.size() - 1; ++i) {
if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) {
continue;
}
for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) {
int tmp_c = static_cast<int>(i);
int tmp_r = static_cast<int>(P_indices[idx]);
tmp(tmp_r, tmp_c) = static_cast<float>(P_data[idx]);
}
}
AINFO << "row number: " << r;
AINFO << "col number: " << c;
for (int i = 0; i < r; ++i) {
AINFO << "row number: " << i;
AINFO << tmp.row(i);
}
}
void DualVariableWarmStartSlackOSQPInterface::assembleA(
const int r, const int c, const std::vector<c_float>& P_data,
const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) {
constraint_A_ = Eigen::MatrixXf::Zero(r, c);
for (size_t i = 0; i < P_indptr.size() - 1; ++i) {
if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) {
continue;
}
for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) {
int tmp_c = static_cast<int>(i);
int tmp_r = static_cast<int>(P_indices[idx]);
constraint_A_(tmp_r, tmp_c) = static_cast<float>(P_data[idx]);
}
}
}
bool DualVariableWarmStartSlackOSQPInterface::optimize() {
// int kNumParam = num_of_variables_;
// int kNumConst = num_of_constraints_;
bool succ = true;
// assemble P, quadratic term in objective
std::vector<c_float> P_data;
std::vector<c_int> P_indices;
std::vector<c_int> P_indptr;
assembleP(&P_data, &P_indices, &P_indptr);
if (check_mode_) {
AINFO << "print P_data in whole: ";
printMatrix(num_of_variables_, num_of_variables_, P_data, P_indices,
P_indptr);
}
// assemble q, linear term in objective, \sum{beta * slacks}
c_float q[num_of_variables_]; // NOLINT
for (int i = 0; i < num_of_variables_; ++i) {
q[i] = 0.0;
if (i >= s_start_index_) {
q[i] = beta_;
}
}
// assemble A, linear term in constraints
std::vector<c_float> A_data;
std::vector<c_int> A_indices;
std::vector<c_int> A_indptr;
assembleConstraint(&A_data, &A_indices, &A_indptr);
if (check_mode_) {
AINFO << "print A_data in whole: ";
printMatrix(num_of_constraints_, num_of_variables_, A_data, A_indices,
A_indptr);
assembleA(num_of_constraints_, num_of_variables_, A_data, A_indices,
A_indptr);
}
// assemble lb & ub, slack_variable <= 0
c_float lb[num_of_constraints_]; // NOLINT
c_float ub[num_of_constraints_]; // NOLINT
int slack_indx = num_of_constraints_ - slack_horizon_;
for (int i = 0; i < num_of_constraints_; ++i) {
lb[i] = 0.0;
if (i >= slack_indx) {
lb[i] = -2e19;
}
if (i < 2 * obstacles_num_ * (horizon_ + 1)) {
ub[i] = 0.0;
} else if (i < slack_indx) {
ub[i] = 2e19;
} else {
ub[i] = 0.0;
}
}
// Problem settings
OSQPSettings* settings =
reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings)));
// Define Solver settings as default
osqp_set_default_settings(settings);
settings->alpha = osqp_config_.alpha(); // Change alpha parameter
settings->eps_abs = osqp_config_.eps_abs();
settings->eps_rel = osqp_config_.eps_rel();
settings->max_iter = osqp_config_.max_iter();
settings->polish = osqp_config_.polish();
settings->verbose = osqp_config_.osqp_debug_log();
// Populate data
OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
data->n = num_of_variables_;
data->m = num_of_constraints_;
data->P = csc_matrix(data->n, data->n, P_data.size(), P_data.data(),
P_indices.data(), P_indptr.data());
data->q = q;
data->A = csc_matrix(data->m, data->n, A_data.size(), A_data.data(),
A_indices.data(), A_indptr.data());
data->l = lb;
data->u = ub;
// Workspace
OSQPWorkspace* work = nullptr;
// osqp_setup(&work, data, settings);
work = osqp_setup(data, settings);
// Solve Problem
osqp_solve(work);
// check state
if (work->info->status_val != 1 && work->info->status_val != 2) {
AWARN << "OSQP dual warm up unsuccess, "
<< "return status: " << work->info->status;
succ = false;
}
// transfer to make lambda's norm under 1
std::vector<double> lambda_norm;
int l_index = l_start_index_;
for (int i = 0; i < horizon_ + 1; ++i) {
int edges_counter = 0;
for (int j = 0; j < obstacles_num_; ++j) {
int current_edges_num = obstacles_edges_num_(j, 0);
Eigen::MatrixXd Aj =
obstacles_A_.block(edges_counter, 0, current_edges_num, 2);
double tmp1 = 0;
double tmp2 = 0;
for (int k = 0; k < current_edges_num; ++k) {
tmp1 += Aj(k, 0) * work->solution->x[l_index + k];
tmp2 += Aj(k, 1) * work->solution->x[l_index + k];
}
// norm(A * lambda)
double tmp_norm = tmp1 * tmp1 + tmp2 * tmp2;
if (tmp_norm >= 1e-5) {
lambda_norm.push_back(0.75 / std::sqrt(tmp_norm));
} else {
lambda_norm.push_back(0.0);
}
edges_counter += current_edges_num;
l_index += current_edges_num;
}
}
// extract primal results
int variable_index = 0;
// 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0,
// horizon_l
for (int i = 0; i < horizon_ + 1; ++i) {
int r_index = 0;
for (int j = 0; j < obstacles_num_; ++j) {
for (int k = 0; k < obstacles_edges_num_(j, 0); ++k) {
l_warm_up_(r_index, i) = lambda_norm[i * obstacles_num_ + j] *
work->solution->x[variable_index];
++variable_index;
++r_index;
}
}
}
// 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_]
for (int i = 0; i < horizon_ + 1; ++i) {
int r_index = 0;
for (int j = 0; j < obstacles_num_; ++j) {
for (int k = 0; k < 4; ++k) {
n_warm_up_(r_index, i) = lambda_norm[i * obstacles_num_ + j] *
work->solution->x[variable_index];
++r_index;
++variable_index;
}
}
}
// 3. slack variables
for (int i = 0; i < horizon_ + 1; ++i) {
for (int j = 0; j < obstacles_num_; ++j) {
slacks_(j, i) = lambda_norm[i * obstacles_num_ + j] *
work->solution->x[variable_index];
++variable_index;
}
}
succ = succ & (work->info->obj_val <= 1.0);
// Cleanup
osqp_cleanup(work);
c_free(data->A);
c_free(data->P);
c_free(data);
c_free(settings);
return succ;
}
void DualVariableWarmStartSlackOSQPInterface::checkSolution(
const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up) {
// TODO(Runxin): extend
}
void DualVariableWarmStartSlackOSQPInterface::assembleP(
std::vector<c_float>* P_data, std::vector<c_int>* P_indices,
std::vector<c_int>* P_indptr) {
// the objective function is norm(A' * lambda)
std::vector<c_float> P_tmp;
int edges_counter = 0;
for (int j = 0; j < obstacles_num_; ++j) {
int current_edges_num = obstacles_edges_num_(j, 0);
Eigen::MatrixXd Aj;
Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2);
// Eigen::MatrixXd AAj(current_edges_num, current_edges_num);
Aj = Aj * Aj.transpose();
CHECK_EQ(current_edges_num, Aj.cols());
CHECK_EQ(current_edges_num, Aj.rows());
for (int c = 0; c < current_edges_num; ++c) {
for (int r = 0; r < current_edges_num; ++r) {
P_tmp.emplace_back(Aj(r, c));
}
}
// Update index
edges_counter += current_edges_num;
}
int l_index = l_start_index_;
int first_row_location = 0;
// the objective function is norm(A' * lambda)
for (int i = 0; i < horizon_ + 1; ++i) {
edges_counter = 0;
for (auto item : P_tmp) {
P_data->emplace_back(item);
}
// current assumption: stationary obstacles
for (int j = 0; j < obstacles_num_; ++j) {
int current_edges_num = obstacles_edges_num_(j, 0);
for (int c = 0; c < current_edges_num; ++c) {
P_indptr->emplace_back(first_row_location);
for (int r = 0; r < current_edges_num; ++r) {
P_indices->emplace_back(r + l_index);
}
first_row_location += current_edges_num;
}
// Update index
edges_counter += current_edges_num;
l_index += current_edges_num;
}
}
CHECK_EQ(P_indptr->size(), static_cast<size_t>(lambda_horizon_));
for (int i = lambda_horizon_; i < num_of_variables_ + 1; ++i) {
P_indptr->emplace_back(first_row_location);
}
CHECK_EQ(P_data->size(), P_indices->size());
CHECK_EQ(P_indptr->size(), static_cast<size_t>(num_of_variables_) + 1);
}
void DualVariableWarmStartSlackOSQPInterface::assembleConstraint(
std::vector<c_float>* A_data, std::vector<c_int>* A_indices,
std::vector<c_int>* A_indptr) {
/*
* The constraint matrix is as the form,
* |R' * A', G', 0|, #: 2 * obstacles_num_ * (horizon_ + 1)
* |A * t - b, -g, I|, #: obstacles_num_ * (horizon_ + 1)
* |I, 0, 0|, #: num_of_lambda
* |0, I, 0|, #: num_of_miu
* |0, 0, I|, #: num_of_slack
*/
int r1_index = 0;
int r2_index = 2 * obstacles_num_ * (horizon_ + 1);
int r3_index = 3 * obstacles_num_ * (horizon_ + 1);
int r4_index = 3 * obstacles_num_ * (horizon_ + 1) + lambda_horizon_;
int r5_index = r4_index + miu_horizon_;
int first_row_location = 0;
// lambda variables
// lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1);
for (int i = 0; i < horizon_ + 1; ++i) {
int edges_counter = 0;
Eigen::MatrixXd R(2, 2);
R << cos(xWS_(2, i)), sin(xWS_(2, i)), sin(xWS_(2, i)), cos(xWS_(2, i));
Eigen::MatrixXd t_trans(1, 2);
t_trans << (xWS_(0, i) + cos(xWS_(2, i)) * offset_),
(xWS_(1, i) + sin(xWS_(2, i)) * offset_);
// assume: stationary obstacles
for (int j = 0; j < obstacles_num_; ++j) {
int current_edges_num = obstacles_edges_num_(j, 0);
Eigen::MatrixXd Aj =
obstacles_A_.block(edges_counter, 0, current_edges_num, 2);
Eigen::MatrixXd bj =
obstacles_b_.block(edges_counter, 0, current_edges_num, 1);
Eigen::MatrixXd r1_block(2, current_edges_num);
r1_block = R * Aj.transpose();
Eigen::MatrixXd r2_block(1, current_edges_num);
r2_block = t_trans * Aj.transpose() - bj.transpose();
// insert into A matrix, col by col
for (int k = 0; k < current_edges_num; ++k) {
A_data->emplace_back(r1_block(0, k));
A_indices->emplace_back(r1_index);
A_data->emplace_back(r1_block(1, k));
A_indices->emplace_back(r1_index + 1);
A_data->emplace_back(r2_block(0, k));
A_indices->emplace_back(r2_index);
A_data->emplace_back(1.0);
A_indices->emplace_back(r3_index);
r3_index++;
A_indptr->emplace_back(first_row_location);
first_row_location += 4;
}
// Update index
edges_counter += current_edges_num;
r1_index += 2;
r2_index += 1;
}
}
// miu variables, miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1);
// G: ((1, 0, -1, 0), (0, 1, 0, -1))
// g: g_
r1_index = 0;
r2_index = 2 * obstacles_num_ * (horizon_ + 1);
for (int i = 0; i < horizon_ + 1; ++i) {
for (int j = 0; j < obstacles_num_; ++j) {
for (int k = 0; k < 4; ++k) {
// update G
if (k < 2) {
A_data->emplace_back(1.0);
} else {
A_data->emplace_back(-1.0);
}
A_indices->emplace_back(r1_index + k % 2);
// update g'
A_data->emplace_back(-g_[k]);
A_indices->emplace_back(r2_index);
// update I
A_data->emplace_back(1.0);
A_indices->emplace_back(r4_index);
r4_index++;
// update col index
A_indptr->emplace_back(first_row_location);
first_row_location += 3;
}
// update index
r1_index += 2;
r2_index += 1;
}
}
// slack variables
// slack_horizon_ = obstacles_edges_sum_ * (horizon_ + 1);
r2_index = 2 * obstacles_num_ * (horizon_ + 1);
for (int i = 0; i < horizon_ + 1; ++i) {
for (int j = 0; j < obstacles_num_; ++j) {
A_data->emplace_back(1.0);
A_indices->emplace_back(r2_index);
++r2_index;
A_data->emplace_back(1.0);
A_indices->emplace_back(r5_index);
++r5_index;
A_indptr->emplace_back(first_row_location);
first_row_location += 2;
}
}
A_indptr->emplace_back(first_row_location);
CHECK_EQ(A_data->size(), A_indices->size());
CHECK_EQ(A_indptr->size(), static_cast<size_t>(num_of_variables_) + 1);
}
void DualVariableWarmStartSlackOSQPInterface::get_optimization_results(
Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up,
Eigen::MatrixXd* s_warm_up) const {
*l_warm_up = l_warm_up_;
*n_warm_up = n_warm_up_;
*s_warm_up = slacks_;
// debug mode check slack values
double max_s = slacks_(0, 0);
double min_s = slacks_(0, 0);
for (int i = 0; i < horizon_ + 1; ++i) {
for (int j = 0; j < obstacles_num_; ++j) {
max_s = std::max(max_s, slacks_(j, i));
min_s = std::min(min_s, slacks_(j, i));
}
}
ADEBUG << "max_s: " << max_s;
ADEBUG << "min_s: " << min_s;
}
} // namespace planning
} // namespace apollo
| ApolloAuto/apollo | modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_interface.cc | C++ | apache-2.0 | 17,011 |
package info.bati11.wearprofile;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
public class AboutActivity extends Activity {
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, AboutActivity.class);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
| bati11/wear-profile | mobile/src/main/java/info/bati11/wearprofile/AboutActivity.java | Java | apache-2.0 | 964 |