code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
# Euosma callosa (F.Muell.) Kuntze SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Logania callosa F.Muell.
### Remarks
null
|
Java
|
## toast-with-duration-headref
#### Toast with duration


*Syntax*
{% codetabs name="React Native", type="js" -%}
import React, { Component } from "react";
import { Container, Header, Content, Text, Button, Toast } from "native-base";
export default class ToastDuration extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false
};
}
render() {
return (
<Container>
<Header />
<Content padder>
<Button
onPress={() =>
Toast.show({
text: "Wrong password!",
buttonText: "Okay",
duration: 3000
})}
>
<Text>Toast</Text>
</Button>
</Content>
</Container>
);
}
}
{%- language name="Vue Native", type="vue" -%}
<template>
<nb-container>
<nb-header />
<nb-content padder>
<nb-button :onPress="handleBtnPress">
<nb-text>Toast</nb-text>
</nb-button>
</nb-content>
</nb-container>
</template>
<script>
import React from "react";
import { Toast } from "native-base";
export default {
methods: {
handleBtnPress: function() {
Toast.show({
text: "Wrong password!",
buttonText: "Okay",
duration: 3000
});
}
}
};
</script>
{%- endcodetabs %}
<p>
<div id="" class="mobileDevice" style="background: url("https://docs-v2.nativebase.io/docs/assets/iosphone.png") no-repeat; padding: 63px 20px 100px 15px; width: 292px; height: 600px;margin:0 auto;float:none;">
<img src="https://github.com/GeekyAnts/NativeBase-KitchenSink/raw/v2.6.1/screenshots/ios/toast-duration.gif" alt="" style="display:block !important" />
</div>
</p>
<br />
|
Java
|
package de.jungblut.math.squashing;
import de.jungblut.math.DoubleMatrix;
import de.jungblut.math.MathUtils;
/**
* Logistic error function implementation.
*
* @author thomas.jungblut
*
*/
public final class LogisticErrorFunction implements ErrorFunction {
@Override
public double calculateError(DoubleMatrix y, DoubleMatrix hypothesis) {
return (y.multiply(-1d)
.multiplyElementWise(MathUtils.logMatrix(hypothesis)).subtract((y
.subtractBy(1.0d)).multiplyElementWise(MathUtils.logMatrix(hypothesis
.subtractBy(1d))))).sum();
}
}
|
Java
|
"""
Django settings for sparta project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'sparta.urls'
WSGI_APPLICATION = 'sparta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER':'root',
'NAME':'fordjango',
'PASSWORD':'123456',
'HOST':'localhost',
'PORT':''
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static')
STATIC_URL = '/assets/'
STATICFILES_DIRS = (
'/home/dexter/weaponx/Django/sparta/sparta/assets',
)
TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',)
|
Java
|
namespace CJia.PIVAS.App.UI
{
partial class BatchIllfieldLabelCollectReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrIllfield = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchZ = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchB = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchW = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchL = new DevExpress.XtraReports.UI.XRTableCell();
this.xrAllBatch = new DevExpress.XtraReports.UI.XRTableCell();
this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand();
this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xlZX = new DevExpress.XtraReports.UI.XRLabel();
this.xlZXDate = new DevExpress.XtraReports.UI.XRLabel();
this.xlKDDate = new DevExpress.XtraReports.UI.XRLabel();
this.xlKD1 = new DevExpress.XtraReports.UI.XRLabel();
this.xrDY1 = new DevExpress.XtraReports.UI.XRLabel();
this.xlDYstart = new DevExpress.XtraReports.UI.XRLabel();
this.xrDY2 = new DevExpress.XtraReports.UI.XRLabel();
this.xlDYEnd = new DevExpress.XtraReports.UI.XRLabel();
this.xrRepertHeader = new DevExpress.XtraReports.UI.XRLabel();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.xrLabel8 = new DevExpress.XtraReports.UI.XRLabel();
this.xrPrintBy = new DevExpress.XtraReports.UI.XRLabel();
this.lblPrintDate = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel6 = new DevExpress.XtraReports.UI.XRLabel();
this.xrPageInfo1 = new DevExpress.XtraReports.UI.XRPageInfo();
this.xr = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
this.Detail.HeightF = 25.95833F;
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// xrTable1
//
this.xrTable1.LocationFloat = new DevExpress.Utils.PointFloat(16.49996F, 0F);
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.SizeF = new System.Drawing.SizeF(823.5001F, 25F);
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrIllfield,
this.xrBatchZ,
this.xrBatch1,
this.xrBatch2,
this.xrBatch3,
this.xrBatch4,
this.xrBatch5,
this.xrBatch6,
this.xrBatchB,
this.xrBatchW,
this.xrBatchL,
this.xrAllBatch});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1D;
//
// xrIllfield
//
this.xrIllfield.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrIllfield.Name = "xrIllfield";
this.xrIllfield.StylePriority.UseBorders = false;
this.xrIllfield.StylePriority.UseTextAlignment = false;
this.xrIllfield.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrIllfield.Weight = 0.56262541342602934D;
//
// xrBatchZ
//
this.xrBatchZ.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchZ.Name = "xrBatchZ";
this.xrBatchZ.StylePriority.UseBorders = false;
this.xrBatchZ.StylePriority.UseTextAlignment = false;
this.xrBatchZ.Text = "xrBatchZ";
this.xrBatchZ.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchZ.Weight = 0.21932980514517925D;
//
// xrBatch1
//
this.xrBatch1.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch1.Name = "xrBatch1";
this.xrBatch1.StylePriority.UseBorders = false;
this.xrBatch1.StylePriority.UseTextAlignment = false;
this.xrBatch1.Text = "xrBatch1";
this.xrBatch1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch1.Weight = 0.21932980955029355D;
//
// xrBatch2
//
this.xrBatch2.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch2.Name = "xrBatch2";
this.xrBatch2.StylePriority.UseBorders = false;
this.xrBatch2.StylePriority.UseTextAlignment = false;
this.xrBatch2.Text = "xrBatch2";
this.xrBatch2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch2.Weight = 0.21932981924775033D;
//
// xrBatch3
//
this.xrBatch3.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch3.Name = "xrBatch3";
this.xrBatch3.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F);
this.xrBatch3.StylePriority.UseBorders = false;
this.xrBatch3.StylePriority.UsePadding = false;
this.xrBatch3.StylePriority.UseTextAlignment = false;
this.xrBatch3.Text = "xrBatch3";
this.xrBatch3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch3.Weight = 0.21932982002991075D;
//
// xrBatch4
//
this.xrBatch4.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch4.Name = "xrBatch4";
this.xrBatch4.StylePriority.UseBorders = false;
this.xrBatch4.StylePriority.UseTextAlignment = false;
this.xrBatch4.Text = "xrBatch4";
this.xrBatch4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch4.Weight = 0.21932980591515972D;
//
// xrBatch5
//
this.xrBatch5.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch5.Name = "xrBatch5";
this.xrBatch5.StylePriority.UseBorders = false;
this.xrBatch5.StylePriority.UseTextAlignment = false;
this.xrBatch5.Text = "xrBatch5";
this.xrBatch5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch5.Weight = 0.21932981354501713D;
//
// xrBatch6
//
this.xrBatch6.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch6.Name = "xrBatch6";
this.xrBatch6.StylePriority.UseBorders = false;
this.xrBatch6.StylePriority.UseTextAlignment = false;
this.xrBatch6.Text = "xrBatch6";
this.xrBatch6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch6.Weight = 0.21932980797892387D;
//
// xrBatchB
//
this.xrBatchB.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchB.Name = "xrBatchB";
this.xrBatchB.StylePriority.UseBorders = false;
this.xrBatchB.StylePriority.UseTextAlignment = false;
this.xrBatchB.Text = "xrBatchB";
this.xrBatchB.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchB.Weight = 0.2193298025618684D;
//
// xrBatchW
//
this.xrBatchW.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchW.Name = "xrBatchW";
this.xrBatchW.StylePriority.UseBorders = false;
this.xrBatchW.StylePriority.UseTextAlignment = false;
this.xrBatchW.Text = "xrBatchW";
this.xrBatchW.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchW.Weight = 0.21932980514517925D;
//
// xrBatchL
//
this.xrBatchL.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchL.Name = "xrBatchL";
this.xrBatchL.StylePriority.UseBorders = false;
this.xrBatchL.StylePriority.UseTextAlignment = false;
this.xrBatchL.Text = "xrBatchL";
this.xrBatchL.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchL.Weight = 0.21932980436755359D;
//
// xrAllBatch
//
this.xrAllBatch.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrAllBatch.Name = "xrAllBatch";
this.xrAllBatch.StylePriority.UseBorders = false;
this.xrAllBatch.StylePriority.UseTextAlignment = false;
this.xrAllBatch.Text = "xrAllBatch";
this.xrAllBatch.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrAllBatch.Weight = 0.25437855038829715D;
//
// TopMargin
//
this.TopMargin.HeightF = 42F;
this.TopMargin.Name = "TopMargin";
this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// BottomMargin
//
this.BottomMargin.HeightF = 34.24994F;
this.BottomMargin.Name = "BottomMargin";
this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xlZX,
this.xlZXDate,
this.xlKDDate,
this.xlKD1,
this.xrDY1,
this.xlDYstart,
this.xrDY2,
this.xlDYEnd,
this.xrRepertHeader});
this.ReportHeader.HeightF = 111.1667F;
this.ReportHeader.Name = "ReportHeader";
//
// xlZX
//
this.xlZX.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xlZX.LocationFloat = new DevExpress.Utils.PointFloat(633.5764F, 78.16674F);
this.xlZX.Name = "xlZX";
this.xlZX.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlZX.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xlZX.StylePriority.UseFont = false;
this.xlZX.StylePriority.UseTextAlignment = false;
this.xlZX.Text = "执行日期:";
this.xlZX.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlZX.Visible = false;
//
// xlZXDate
//
this.xlZXDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlZXDate.LocationFloat = new DevExpress.Utils.PointFloat(716.1702F, 78.16674F);
this.xlZXDate.Name = "xlZXDate";
this.xlZXDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlZXDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F);
this.xlZXDate.StylePriority.UseFont = false;
this.xlZXDate.StylePriority.UseTextAlignment = false;
this.xlZXDate.Text = "2222/22/22";
this.xlZXDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlZXDate.Visible = false;
//
// xlKDDate
//
this.xlKDDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlKDDate.LocationFloat = new DevExpress.Utils.PointFloat(525.2031F, 78.16674F);
this.xlKDDate.Name = "xlKDDate";
this.xlKDDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlKDDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F);
this.xlKDDate.StylePriority.UseFont = false;
this.xlKDDate.StylePriority.UseTextAlignment = false;
this.xlKDDate.Text = "2222/22/22";
this.xlKDDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlKDDate.Visible = false;
//
// xlKD1
//
this.xlKD1.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xlKD1.LocationFloat = new DevExpress.Utils.PointFloat(442.6093F, 78.16674F);
this.xlKD1.Name = "xlKD1";
this.xlKD1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlKD1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xlKD1.StylePriority.UseFont = false;
this.xlKD1.StylePriority.UseTextAlignment = false;
this.xlKD1.Text = "开单日期:";
this.xlKD1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlKD1.Visible = false;
//
// xrDY1
//
this.xrDY1.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrDY1.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 78.16671F);
this.xrDY1.Name = "xrDY1";
this.xrDY1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrDY1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xrDY1.StylePriority.UseFont = false;
this.xrDY1.StylePriority.UseTextAlignment = false;
this.xrDY1.Text = "打印时间:";
this.xrDY1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrDY1.Visible = false;
//
// xlDYstart
//
this.xlDYstart.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlDYstart.LocationFloat = new DevExpress.Utils.PointFloat(101.5938F, 78.16671F);
this.xlDYstart.Name = "xlDYstart";
this.xlDYstart.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlDYstart.SizeF = new System.Drawing.SizeF(156.8757F, 23.00002F);
this.xlDYstart.StylePriority.UseFont = false;
this.xlDYstart.StylePriority.UseTextAlignment = false;
this.xlDYstart.Text = "2222/22/22 22:33:33";
this.xlDYstart.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlDYstart.Visible = false;
//
// xrDY2
//
this.xrDY2.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrDY2.LocationFloat = new DevExpress.Utils.PointFloat(258.4695F, 78.16671F);
this.xrDY2.Name = "xrDY2";
this.xrDY2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrDY2.SizeF = new System.Drawing.SizeF(27.2641F, 23.00001F);
this.xrDY2.StylePriority.UseFont = false;
this.xrDY2.StylePriority.UseTextAlignment = false;
this.xrDY2.Text = "~";
this.xrDY2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrDY2.Visible = false;
//
// xlDYEnd
//
this.xlDYEnd.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlDYEnd.LocationFloat = new DevExpress.Utils.PointFloat(285.7336F, 78.16671F);
this.xlDYEnd.Name = "xlDYEnd";
this.xlDYEnd.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlDYEnd.SizeF = new System.Drawing.SizeF(156.8757F, 22.99998F);
this.xlDYEnd.StylePriority.UseFont = false;
this.xlDYEnd.StylePriority.UseTextAlignment = false;
this.xlDYEnd.Text = "2222/22/22 22:33:33";
this.xlDYEnd.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlDYEnd.Visible = false;
//
// xrRepertHeader
//
this.xrRepertHeader.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold);
this.xrRepertHeader.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 10.00001F);
this.xrRepertHeader.Name = "xrRepertHeader";
this.xrRepertHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrRepertHeader.SizeF = new System.Drawing.SizeF(823.4999F, 45.91666F);
this.xrRepertHeader.StylePriority.UseFont = false;
this.xrRepertHeader.StylePriority.UseTextAlignment = false;
this.xrRepertHeader.Text = "瓶贴汇总";
this.xrRepertHeader.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel8,
this.xrPrintBy,
this.lblPrintDate,
this.xrLabel6,
this.xrPageInfo1});
this.ReportFooter.HeightF = 60.66672F;
this.ReportFooter.Name = "ReportFooter";
//
// xrLabel8
//
this.xrLabel8.Font = new System.Drawing.Font("Times New Roman", 9F);
this.xrLabel8.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 10.00001F);
this.xrLabel8.Multiline = true;
this.xrLabel8.Name = "xrLabel8";
this.xrLabel8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel8.SizeF = new System.Drawing.SizeF(67.70834F, 23F);
this.xrLabel8.StylePriority.UseFont = false;
this.xrLabel8.StylePriority.UseTextAlignment = false;
this.xrLabel8.Text = "打印人:\r\n";
this.xrLabel8.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// xrPrintBy
//
this.xrPrintBy.Font = new System.Drawing.Font("Times New Roman", 9F);
this.xrPrintBy.LocationFloat = new DevExpress.Utils.PointFloat(86.70836F, 10.00001F);
this.xrPrintBy.Name = "xrPrintBy";
this.xrPrintBy.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrPrintBy.SizeF = new System.Drawing.SizeF(134.375F, 22.99999F);
this.xrPrintBy.StylePriority.UseFont = false;
this.xrPrintBy.StylePriority.UseTextAlignment = false;
this.xrPrintBy.Text = "xrPrintBy";
this.xrPrintBy.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// lblPrintDate
//
this.lblPrintDate.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.lblPrintDate.LocationFloat = new DevExpress.Utils.PointFloat(699.4152F, 10.00001F);
this.lblPrintDate.Name = "lblPrintDate";
this.lblPrintDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.lblPrintDate.SizeF = new System.Drawing.SizeF(145.4509F, 23.00002F);
this.lblPrintDate.StylePriority.UseFont = false;
this.lblPrintDate.StylePriority.UseTextAlignment = false;
this.lblPrintDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// xrLabel6
//
this.xrLabel6.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrLabel6.LocationFloat = new DevExpress.Utils.PointFloat(602.238F, 10.00001F);
this.xrLabel6.Name = "xrLabel6";
this.xrLabel6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel6.SizeF = new System.Drawing.SizeF(97.17715F, 23.00001F);
this.xrLabel6.StylePriority.UseFont = false;
this.xrLabel6.StylePriority.UseTextAlignment = false;
this.xrLabel6.Text = "打印时间:";
this.xrLabel6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleRight;
//
// xrPageInfo1
//
this.xrPageInfo1.LocationFloat = new DevExpress.Utils.PointFloat(770.4121F, 33.00002F);
this.xrPageInfo1.Name = "xrPageInfo1";
this.xrPageInfo1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrPageInfo1.SizeF = new System.Drawing.SizeF(50F, 23F);
//
// xr
//
this.xr.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xr.Name = "xr";
this.xr.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F);
this.xr.StylePriority.UseBorders = false;
this.xr.StylePriority.UsePadding = false;
this.xr.StylePriority.UseTextAlignment = false;
this.xr.Text = "第2批";
this.xr.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xr.Weight = 0.21635782812123941D;
//
// xrTableCell3
//
this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseBorders = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
this.xrTableCell3.Text = "第1批";
this.xrTableCell3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell3.Weight = 0.21635782165233986D;
//
// xrTableCell2
//
this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseBorders = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
this.xrTableCell2.Text = "早上批";
this.xrTableCell2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell2.Weight = 0.21635782739762832D;
//
// xrTableCell4
//
this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
this.xrTableCell4.Text = "病区\\批次";
this.xrTableCell4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell4.Weight = 0.55500149632994178D;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell2,
this.xrTableCell3,
this.xr,
this.xrTableCell1,
this.xrTableCell8,
this.xrTableCell9,
this.xrTableCell10,
this.xrTableCell11,
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell7});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 1D;
//
// xrTableCell1
//
this.xrTableCell1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseBorders = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
this.xrTableCell1.Text = "第3批";
this.xrTableCell1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell1.Weight = 0.21635793591515309D;
//
// xrTableCell8
//
this.xrTableCell8.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
this.xrTableCell8.Text = "第4批";
this.xrTableCell8.Weight = 0.21635784117031898D;
//
// xrTableCell9
//
this.xrTableCell9.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseBorders = false;
this.xrTableCell9.Text = "第5批";
this.xrTableCell9.Weight = 0.21635794209431053D;
//
// xrTableCell10
//
this.xrTableCell10.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseBorders = false;
this.xrTableCell10.Text = "第6批";
this.xrTableCell10.Weight = 0.21635761118606367D;
//
// xrTableCell11
//
this.xrTableCell11.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseBorders = false;
this.xrTableCell11.Text = "打包";
this.xrTableCell11.Weight = 0.21635761118606367D;
//
// xrTableCell5
//
this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseBorders = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
this.xrTableCell5.Text = "打包2";
this.xrTableCell5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell5.Weight = 0.2163580562136298D;
//
// xrTableCell6
//
this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
this.xrTableCell6.Text = "临时";
this.xrTableCell6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell6.Weight = 0.21635783261726718D;
//
// xrTableCell7
//
this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
this.xrTableCell7.StylePriority.UseTextAlignment = false;
this.xrTableCell7.Text = "全部批次";
this.xrTableCell7.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell7.Weight = 0.25093144098893139D;
//
// xrTable3
//
this.xrTable3.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 0F);
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3});
this.xrTable3.SizeF = new System.Drawing.SizeF(823.5F, 25F);
this.xrTable3.StylePriority.UseTextAlignment = false;
this.xrTable3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
//
// GroupHeader1
//
this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable3});
this.GroupHeader1.HeightF = 25F;
this.GroupHeader1.Name = "GroupHeader1";
//
// BatchIllfieldLabelCollectReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.ReportHeader,
this.ReportFooter,
this.BottomMargin,
this.Detail,
this.TopMargin,
this.GroupHeader1});
this.Margins = new System.Drawing.Printing.Margins(0, 0, 42, 34);
this.Version = "12.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.TopMarginBand TopMargin;
private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRLabel lblPrintDate;
private DevExpress.XtraReports.UI.XRLabel xrLabel6;
private DevExpress.XtraReports.UI.XRLabel xrRepertHeader;
private DevExpress.XtraReports.UI.XRPageInfo xrPageInfo1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrIllfield;
private DevExpress.XtraReports.UI.XRTableCell xrBatch1;
private DevExpress.XtraReports.UI.XRTableCell xrBatch2;
private DevExpress.XtraReports.UI.XRTableCell xrBatch3;
private DevExpress.XtraReports.UI.XRLabel xrLabel8;
private DevExpress.XtraReports.UI.XRLabel xrPrintBy;
private DevExpress.XtraReports.UI.XRTableCell xr;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrBatch4;
private DevExpress.XtraReports.UI.XRTableCell xrBatch5;
private DevExpress.XtraReports.UI.XRTableCell xrBatch6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrAllBatch;
private DevExpress.XtraReports.UI.XRTableCell xrBatchZ;
private DevExpress.XtraReports.UI.XRTableCell xrBatchB;
private DevExpress.XtraReports.UI.XRTableCell xrBatchL;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRLabel xrDY1;
private DevExpress.XtraReports.UI.XRLabel xlDYstart;
private DevExpress.XtraReports.UI.XRLabel xrDY2;
private DevExpress.XtraReports.UI.XRLabel xlDYEnd;
private DevExpress.XtraReports.UI.XRLabel xlKDDate;
private DevExpress.XtraReports.UI.XRLabel xlKD1;
private DevExpress.XtraReports.UI.XRTableCell xrBatchW;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRLabel xlZX;
private DevExpress.XtraReports.UI.XRLabel xlZXDate;
}
}
|
Java
|
{% include header_product.html%}
<div class="company-section">
<div class="container">
<div class="company-text">
<h1 class="company-title">Company</h1>
<div class="client-text-section">
{{ content }}
</div>
</div>
</div>
</div>
{% include contact_info.html %}
{% include footer.html %}
|
Java
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.geolocation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory;
import org.appcelerator.titanium.util.TiConvert;
import ti.modules.titanium.geolocation.TiLocation.GeocodeResponseHandler;
import ti.modules.titanium.geolocation.android.AndroidModule;
import ti.modules.titanium.geolocation.android.LocationProviderProxy;
import ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener;
import ti.modules.titanium.geolocation.android.LocationRuleProxy;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
/**
* GeolocationModule exposes all common methods and properties relating to geolocation behavior
* associated with Ti.Geolocation to the Titanium developer. Only cross platform API points should
* be exposed through this class as Android-only API points or types should be put in a Android module
* under this module.
*
* The GeolocationModule provides management for 3 different location behavior modes (detailed
* descriptions will follow below):
* <ul>
* <li>legacy - existing behavior found in Titanium Mobile 1.7 and 1.8. <b>DEPRECATED</b></li>
* <li>simple - replacement for the old legacy mode that allows for better parity across platforms</li>
* <li>manual - Android-specific mode that exposes full control over the providers and rules</li>
* </ul>
*
* <p>
* <b>Legacy location mode</b>:<br>
* This mode operates on receiving location updates from a single active provider at a time. Settings
* used to pick and register a provider with the OS are pulled from the PROPERTY_ACCURACY, PROPERTY_FREQUENCY
* and PROPERTY_PREFERRED_PROVIDER properties on the module.
* <p>
* The valid accuracy properties for this location mode are ACCURACY_BEST, ACCURACY_NEAREST_TEN_METERS,
* ACCURACY_HUNDRED_METERS, ACCURACY_KILOMETER and ACCURACY_THREE_KILOMETERS. The accuracy property is a
* double value that will be used by the OS as a way to determine how many meters should change in location
* before a new update is sent. Accuracy properties other than this will either be ignored or change the
* current location behavior mode. The frequency property is a double value that is used by the OS to determine
* how much time in milliseconds should pass before a new update is sent.
* <p>
* The OS uses some fuzzy logic to determine the update frequency and these values are treated as no more than
* suggestions. For example: setting the frequency to 0 milliseconds and the accuracy to 10 meters may not
* result in a update being sent as fast as possible which is what frequency of 0 ms indicates. This is due to
* the OS not sending updates till the accuracy property is satisfied. If the desired behavior is to get updates
* purely based on time then the suggested mechanism would be to set the accuracy to 0 meters and then set the
* frequency to the desired update interval in milliseconds.
*
* <p>
* <b>Simple location mode</b>:<br>
* This mode operates on receiving location updates from multiple sources. The simple mode has two states - high
* accuracy and low accuracy. The difference in these two modes is that low accuracy has the passive and network
* providers registered by default where the high accuracy state enables the gps provider in addition to the passive
* and network providers. The simple mode utilizes location rules for filtering location updates to try and fall back
* gracefully (when in high accuracy state) to the network and passive providers if a gps update has not been received
* recently.
* <p>
* No specific controls for time or distance (better terminology in line with native Android docs but these
* are called frequency and accuracy in legacy mode) are exposed to the Titanium developer as the details of this mode
* are supposed to be driven by Appcelerator based on our observations. If greater control on the part of the Titanium
* developer is needed then the manual behavior mode can and should be used.
*
* <p>
* <b>Manual location mode</b>:<br>
* This mode puts full control over providers and rules in the hands of the Titanium developer. The developer will be
* responsible for registering location providers, setting time and distance settings per provider and defining the rule
* set if any rules are desired.
* <p>
* In this mode, the developer would create a Ti.Geolocation.Android.LocationProvider object for each provider they want
* to use and add this to the list of manual providers via addLocationProvider(LocationProviderProxy). In order to set
* rules, the developer will have to create a Ti.Geolocation.Android.LocationRule object per rule and then add those
* rules via addLocationRule(LocationRuleProxy). These rules will be applied to any location updates that come from the
* registered providers. Further information on the LocationProvider and LocationRule objects can be found by looking at
* those specific classes.
*
* <p>
* <b>General location behavior</b>:<br>
* The GeolocationModule is capable of switching modes at any time and keeping settings per mode separated. Changing modes
* is done by updating the Ti.Geolocation.accuracy property. Based on the new value of the accuracy property, the
* legacy or simple modes may be enabled (and the previous mode may be turned off). Enabling or disabling the manual mode
* is done by setting the AndroidModule.manualMode (Ti.Geolocation.Android.manualMode) value. NOTE: updating the location
* rules will not update the mode. Simply setting the Ti.Geolocation.accuracy property will not enable the legacy/simple
* modes if you are currently in the manual mode - you must disable the manual mode before the simple/legacy modes are used
* <p>
* In regards to actually "turning on" the providers by registering them with the OS - this is triggered by the presence of
* "location" event listeners on the GeolocationModule. When the first listener is added, providers start being registered
* with the OS. When there are no listeners then all the providers are de-registered. Changes made to location providers or
* accuracy, frequency properties or even changing modes are respected and kept but don't actually get applied on the OS until
* the listener count is greater than 0.
*/
// TODO deprecate the frequency and preferredProvider property
@Kroll.module(propertyAccessors={
TiC.PROPERTY_ACCURACY,
TiC.PROPERTY_FREQUENCY,
TiC.PROPERTY_PREFERRED_PROVIDER
})
public class GeolocationModule extends KrollModule
implements Handler.Callback, LocationProviderListener
{
// TODO move these to the AndroidModule namespace since they will only be used when creating
// manual location providers
@Kroll.constant @Deprecated public static final String PROVIDER_PASSIVE = LocationManager.PASSIVE_PROVIDER;
@Kroll.constant @Deprecated public static final String PROVIDER_NETWORK = LocationManager.NETWORK_PROVIDER;
@Kroll.constant @Deprecated public static final String PROVIDER_GPS = LocationManager.GPS_PROVIDER;
@Kroll.constant public static final int ACCURACY_LOW = 0;
@Kroll.constant public static final int ACCURACY_HIGH = 1;
@Kroll.constant @Deprecated public static final int ACCURACY_BEST = 2;
@Kroll.constant @Deprecated public static final int ACCURACY_NEAREST_TEN_METERS = 3;
@Kroll.constant @Deprecated public static final int ACCURACY_HUNDRED_METERS = 4;
@Kroll.constant @Deprecated public static final int ACCURACY_KILOMETER = 5;
@Kroll.constant @Deprecated public static final int ACCURACY_THREE_KILOMETERS = 6;
public TiLocation tiLocation;
public AndroidModule androidModule;
public int numLocationListeners = 0;
public HashMap<String, LocationProviderProxy> simpleLocationProviders = new HashMap<String, LocationProviderProxy>();
@Deprecated public HashMap<String, LocationProviderProxy> legacyLocationProviders = new HashMap<String, LocationProviderProxy>();
public boolean legacyModeActive = true;
protected static final int MSG_ENABLE_LOCATION_PROVIDERS = KrollModule.MSG_LAST_ID + 100;
protected static final int MSG_LAST_ID = MSG_ENABLE_LOCATION_PROVIDERS;
private static final String TAG = "GeolocationModule";
private static final double SIMPLE_LOCATION_PASSIVE_DISTANCE = 0.0;
private static final double SIMPLE_LOCATION_PASSIVE_TIME = 0;
private static final double SIMPLE_LOCATION_NETWORK_DISTANCE = 10.0;
private static final double SIMPLE_LOCATION_NETWORK_TIME = 10000;
private static final double SIMPLE_LOCATION_GPS_DISTANCE = 3.0;
private static final double SIMPLE_LOCATION_GPS_TIME = 3000;
private static final double SIMPLE_LOCATION_NETWORK_DISTANCE_RULE = 200;
private static final double SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE = 60000;
private static final double SIMPLE_LOCATION_GPS_MIN_AGE_RULE = 30000;
private TiCompass tiCompass;
private boolean compassListenersRegistered = false;
private boolean sentAnalytics = false;
private ArrayList<LocationRuleProxy> simpleLocationRules = new ArrayList<LocationRuleProxy>();
private LocationRuleProxy simpleLocationGpsRule;
private LocationRuleProxy simpleLocationNetworkRule;
private int simpleLocationAccuracyProperty = ACCURACY_LOW;
private Location currentLocation;
//currentLocation is conditionally updated. lastLocation is unconditionally updated
//since currentLocation determines when to send out updates, and lastLocation is passive
private Location lastLocation;
@Deprecated private HashMap<Integer, Double> legacyLocationAccuracyMap = new HashMap<Integer, Double>();
@Deprecated private int legacyLocationAccuracyProperty = ACCURACY_NEAREST_TEN_METERS;
@Deprecated private double legacyLocationFrequency = 5000;
@Deprecated private String legacyLocationPreferredProvider = PROVIDER_NETWORK;
/**
* Constructor
*/
public GeolocationModule()
{
super("geolocation");
tiLocation = new TiLocation();
tiCompass = new TiCompass(this, tiLocation);
// initialize the legacy location accuracy map
legacyLocationAccuracyMap.put(ACCURACY_BEST, 0.0); // this needs to be 0.0 to work for only time based updates
legacyLocationAccuracyMap.put(ACCURACY_NEAREST_TEN_METERS, 10.0);
legacyLocationAccuracyMap.put(ACCURACY_HUNDRED_METERS, 100.0);
legacyLocationAccuracyMap.put(ACCURACY_KILOMETER, 1000.0);
legacyLocationAccuracyMap.put(ACCURACY_THREE_KILOMETERS, 3000.0);
legacyLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, 10.0f, legacyLocationFrequency, this));
simpleLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE, SIMPLE_LOCATION_NETWORK_TIME, this));
simpleLocationProviders.put(PROVIDER_PASSIVE, new LocationProviderProxy(PROVIDER_PASSIVE, SIMPLE_LOCATION_PASSIVE_DISTANCE, SIMPLE_LOCATION_PASSIVE_TIME, this));
// create these now but we don't want to include these in the rule set unless the simple GPS provider is enabled
simpleLocationGpsRule = new LocationRuleProxy(PROVIDER_GPS, null, SIMPLE_LOCATION_GPS_MIN_AGE_RULE, null);
simpleLocationNetworkRule = new LocationRuleProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE_RULE, SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE, null);
}
/**
* @see org.appcelerator.kroll.KrollProxy#handleMessage(android.os.Message)
*/
@Override
public boolean handleMessage(Message message)
{
switch (message.what) {
case MSG_ENABLE_LOCATION_PROVIDERS: {
Object locationProviders = message.obj;
doEnableLocationProviders((HashMap<String, LocationProviderProxy>) locationProviders);
return true;
}
}
return super.handleMessage(message);
}
private void doAnalytics(Location location)
{
if (!sentAnalytics) {
tiLocation.doAnalytics(location);
sentAnalytics = true;
}
}
/**
* Called by a registered location provider when a location update is received
*
* @param location location update that was received
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onLocationChanged(android.location.Location)
*/
public void onLocationChanged(Location location)
{
lastLocation = location;
if (shouldUseUpdate(location)) {
fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(location, tiLocation.locationManager.getProvider(location.getProvider())));
currentLocation = location;
doAnalytics(location);
}
}
/**
* Called by a registered location provider when its state changes
*
* @param providerName name of the provider whose state has changed
* @param state new state of the provider
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderStateChanged(java.lang.String, int)
*/
public void onProviderStateChanged(String providerName, int state)
{
String message = providerName;
// TODO this is trash. deprecate the existing mechanism of bundling status updates with the
// location event and create a new "locationState" (or whatever) event. for the time being,
// this solution kills my soul slightly less than the previous one
switch (state) {
case LocationProviderProxy.STATE_DISABLED:
message += " is disabled";
Log.i(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_ENABLED:
message += " is enabled";
Log.d(TAG, message, Log.DEBUG_MODE);
break;
case LocationProviderProxy.STATE_OUT_OF_SERVICE:
message += " is out of service";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_UNAVAILABLE:
message += " is unavailable";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_AVAILABLE:
message += " is available";
Log.d(TAG, message, Log.DEBUG_MODE);
break;
case LocationProviderProxy.STATE_UNKNOWN:
message += " is in a unknown state [" + state + "]";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
default:
message += " is in a unknown state [" + state + "]";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
}
}
/**
* Called when the location provider has had one of it's properties updated and thus needs to be re-registered with the OS
*
* @param locationProvider the location provider that needs to be re-registered
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderUpdated(ti.modules.titanium.geolocation.android.LocationProviderProxy)
*/
public void onProviderUpdated(LocationProviderProxy locationProvider)
{
if (getManualMode() && (numLocationListeners > 0)) {
tiLocation.locationManager.removeUpdates(locationProvider);
registerLocationProvider(locationProvider);
}
}
/**
* @see org.appcelerator.kroll.KrollModule#propertyChanged(java.lang.String, java.lang.Object, java.lang.Object, org.appcelerator.kroll.KrollProxy)
*/
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy)
{
if (key.equals(TiC.PROPERTY_ACCURACY)) {
// accuracy property is what triggers a shift between simple and legacy modes. the
// android only manual mode is indicated by the AndroidModule.manualMode value which
// has no impact on the legacyModeActive flag. IE: when determining the current mode,
// both flags must be checked
propertyChangedAccuracy(newValue);
} else if (key.equals(TiC.PROPERTY_FREQUENCY)) {
propertyChangedFrequency(newValue);
} else if (key.equals(TiC.PROPERTY_PREFERRED_PROVIDER)) {
propertyChangedPreferredProvider(newValue);
}
}
/**
* Handles property change for Ti.Geolocation.accuracy
*
* @param newValue new accuracy value
*/
private void propertyChangedAccuracy(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && (!getManualMode()) && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
// is simple mode enabled (registered with OS, not just selected via the accuracy property)
boolean simpleModeEnabled = false;
if (!legacyModeActive && !(getManualMode()) && (numLocationListeners > 0)) {
simpleModeEnabled = true;
}
int accuracyProperty = TiConvert.toInt(newValue);
// is this a legacy accuracy property?
Double accuracyLookupResult = legacyLocationAccuracyMap.get(accuracyProperty);
if (accuracyLookupResult != null) {
// has the value changed from the last known good value?
if (accuracyProperty != legacyLocationAccuracyProperty) {
legacyLocationAccuracyProperty = accuracyProperty;
for (String providerKey : legacyLocationProviders.keySet()) {
LocationProviderProxy locationProvider = legacyLocationProviders.get(providerKey);
locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_DISTANCE, accuracyLookupResult);
}
if (legacyModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
}
if (simpleModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
legacyModeActive = true;
// is this a simple accuracy property?
} else if ((accuracyProperty == ACCURACY_HIGH) || (accuracyProperty == ACCURACY_LOW)) {
// has the value changed from the last known good value?
if (accuracyProperty != simpleLocationAccuracyProperty) {
simpleLocationAccuracyProperty = accuracyProperty;
LocationProviderProxy gpsProvider = simpleLocationProviders.get(PROVIDER_GPS);
if ((accuracyProperty == ACCURACY_HIGH) && (gpsProvider == null)) {
gpsProvider = new LocationProviderProxy(PROVIDER_GPS, SIMPLE_LOCATION_GPS_DISTANCE, SIMPLE_LOCATION_GPS_TIME, this);
simpleLocationProviders.put(PROVIDER_GPS, gpsProvider);
simpleLocationRules.add(simpleLocationNetworkRule);
simpleLocationRules.add(simpleLocationGpsRule);
if (simpleModeEnabled) {
registerLocationProvider(gpsProvider);
}
} else if ((accuracyProperty == ACCURACY_LOW) && (gpsProvider != null)) {
simpleLocationProviders.remove(PROVIDER_GPS);
simpleLocationRules.remove(simpleLocationNetworkRule);
simpleLocationRules.remove(simpleLocationGpsRule);
if (simpleModeEnabled) {
tiLocation.locationManager.removeUpdates(gpsProvider);
}
}
}
if (legacyModeEnabled) {
enableLocationProviders(simpleLocationProviders);
}
legacyModeActive = false;
}
}
/**
* Handles property change for Ti.Geolocation.frequency
*
* @param newValue new frequency value
*/
private void propertyChangedFrequency(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
double frequencyProperty = TiConvert.toDouble(newValue) * 1000;
if (frequencyProperty != legacyLocationFrequency) {
legacyLocationFrequency = frequencyProperty;
Iterator<String> iterator = legacyLocationProviders.keySet().iterator();
while(iterator.hasNext()) {
LocationProviderProxy locationProvider = legacyLocationProviders.get(iterator.next());
locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_TIME, legacyLocationFrequency);
}
if (legacyModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
}
}
/**
* Handles property change for Ti.Geolocation.preferredProvider
*
* @param newValue new preferredProvider value
*/
private void propertyChangedPreferredProvider(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
String preferredProviderProperty = TiConvert.toString(newValue);
if (!(preferredProviderProperty.equals(PROVIDER_NETWORK)) && (!(preferredProviderProperty.equals(PROVIDER_GPS)))) {
return;
}
if (!(preferredProviderProperty.equals(legacyLocationPreferredProvider))) {
LocationProviderProxy oldProvider = legacyLocationProviders.get(legacyLocationPreferredProvider);
LocationProviderProxy newProvider = legacyLocationProviders.get(preferredProviderProperty);
if (oldProvider != null) {
legacyLocationProviders.remove(legacyLocationPreferredProvider);
if (legacyModeEnabled) {
tiLocation.locationManager.removeUpdates(oldProvider);
}
}
if (newProvider == null) {
newProvider = new LocationProviderProxy(preferredProviderProperty, legacyLocationAccuracyMap.get(legacyLocationAccuracyProperty), legacyLocationFrequency, this);
legacyLocationProviders.put(preferredProviderProperty, newProvider);
if (legacyModeEnabled) {
registerLocationProvider(newProvider);
}
}
legacyLocationPreferredProvider = preferredProviderProperty;
}
}
/**
* @see org.appcelerator.kroll.KrollProxy#eventListenerAdded(java.lang.String, int, org.appcelerator.kroll.KrollProxy)
*/
@Override
protected void eventListenerAdded(String event, int count, KrollProxy proxy)
{
if (TiC.EVENT_HEADING.equals(event)) {
if (!compassListenersRegistered) {
tiCompass.registerListener();
compassListenersRegistered = true;
}
} else if (TiC.EVENT_LOCATION.equals(event)) {
numLocationListeners++;
if (numLocationListeners == 1) {
HashMap<String, LocationProviderProxy> locationProviders = legacyLocationProviders;
if (getManualMode()) {
locationProviders = androidModule.manualLocationProviders;
} else if (!legacyModeActive) {
locationProviders = simpleLocationProviders;
}
enableLocationProviders(locationProviders);
// fire off an initial location fix if one is available
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing");
return;
}
lastLocation = tiLocation.getLastKnownLocation();
if (lastLocation != null) {
fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(lastLocation, tiLocation.locationManager.getProvider(lastLocation.getProvider())));
doAnalytics(lastLocation);
}
}
}
super.eventListenerAdded(event, count, proxy);
}
/**
* @see org.appcelerator.kroll.KrollProxy#eventListenerRemoved(java.lang.String, int, org.appcelerator.kroll.KrollProxy)
*/
@Override
protected void eventListenerRemoved(String event, int count, KrollProxy proxy)
{
if (TiC.EVENT_HEADING.equals(event)) {
if (compassListenersRegistered) {
tiCompass.unregisterListener();
compassListenersRegistered = false;
}
} else if (TiC.EVENT_LOCATION.equals(event)) {
numLocationListeners--;
if (numLocationListeners == 0) {
disableLocationProviders();
}
}
super.eventListenerRemoved(event, count, proxy);
}
/**
* Checks if the device has a compass sensor
*
* @return <code>true</code> if the device has a compass, <code>false</code> if not
*/
@Kroll.method @Kroll.getProperty
public boolean getHasCompass()
{
return tiCompass.getHasCompass();
}
/**
* Retrieves the current compass heading and returns it to the specified Javascript function
*
* @param listener Javascript function that will be invoked with the compass heading
*/
@Kroll.method
public void getCurrentHeading(final KrollFunction listener)
{
tiCompass.getCurrentHeading(listener);
}
/**
* Retrieves the last obtained location and returns it as JSON.
*
* @return String representing the last geolocation event
*/
@Kroll.method @Kroll.getProperty
public String getLastGeolocation()
{
return TiAnalyticsEventFactory.locationToJSONString(lastLocation);
}
/**
* Checks if the Android manual location behavior mode is currently enabled
*
* @return <code>true</code> if currently in manual mode, <code>
* false</code> if the Android module has not been registered
* yet with the OS or manual mode is not enabled
*/
private boolean getManualMode()
{
if (androidModule == null) {
return false;
} else {
return androidModule.manualMode;
}
}
@Kroll.method
public boolean hasLocationPermissions()
{
if (Build.VERSION.SDK_INT < 23) {
return true;
}
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
if (currentActivity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
@Kroll.method
public void requestLocationPermissions(@Kroll.argument(optional=true) Object type, @Kroll.argument(optional=true) KrollFunction permissionCallback)
{
if (hasLocationPermissions()) {
return;
}
KrollFunction permissionCB;
if (type instanceof KrollFunction && permissionCallback == null) {
permissionCB = (KrollFunction) type;
} else {
permissionCB = permissionCallback;
}
TiBaseActivity.registerPermissionRequestCallback(TiC.PERMISSION_CODE_LOCATION, permissionCB, getKrollObject());
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
currentActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, TiC.PERMISSION_CODE_LOCATION);
}
/**
* Registers the specified location provider with the OS. Once the provider is registered, the OS
* will begin to provider location updates as they are available
*
* @param locationProvider location provider to be registered
*/
public void registerLocationProvider(LocationProviderProxy locationProvider)
{
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing", Log.DEBUG_MODE);
return;
}
String provider = TiConvert.toString(locationProvider.getProperty(TiC.PROPERTY_NAME));
try {
tiLocation.locationManager.requestLocationUpdates(
provider,
(long) locationProvider.getMinUpdateTime(),
(float) locationProvider.getMinUpdateDistance(),
locationProvider);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to register [" + provider + "], provider is null");
} catch (SecurityException e) {
Log.e(TAG, "Unable to register [" + provider + "], permission denied");
}
}
/**
* Wrapper to ensure task executes on the runtime thread
*
* @param locationProviders list of location providers to enable by registering
* the providers with the OS
*/
public void enableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders)
{
if (KrollRuntime.getInstance().isRuntimeThread()) {
doEnableLocationProviders(locationProviders);
} else {
Message message = getRuntimeHandler().obtainMessage(MSG_ENABLE_LOCATION_PROVIDERS, locationProviders);
message.sendToTarget();
}
}
/**
* Enables the specified location behavior mode by registering the associated
* providers with the OS. Even if the specified mode is currently active, the
* current mode will be disabled by de-registering all the associated providers
* for that mode with the OS and then registering
* them again. This can be useful in cases where the properties for all the
* providers have been updated and they need to be re-registered in order for the
* change to take effect. Modification of the list of providers for any mode
* should occur on the runtime thread in order to make sure threading issues are
* avoiding
*
* @param locationProviders
*/
private void doEnableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders)
{
if (numLocationListeners > 0) {
disableLocationProviders();
Iterator<String> iterator = locationProviders.keySet().iterator();
while(iterator.hasNext()) {
LocationProviderProxy locationProvider = locationProviders.get(iterator.next());
registerLocationProvider(locationProvider);
}
}
}
/**
* Disables the current mode by de-registering all the associated providers
* for that mode with the OS. Providers are just de-registered with the OS,
* not removed from the list of providers we associate with the behavior mode.
*/
private void disableLocationProviders()
{
for (LocationProviderProxy locationProvider : legacyLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
for (LocationProviderProxy locationProvider : simpleLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
if (androidModule != null) {
for (LocationProviderProxy locationProvider : androidModule.manualLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
}
}
/**
* Checks if the device has a valid location service present. The passive location service
* is not counted.
*
* @return <code>true</code> if a valid location service is available on the device,
* <code>false</code> if not
*/
@Kroll.getProperty @Kroll.method
public boolean getLocationServicesEnabled()
{
return tiLocation.getLocationServicesEnabled();
}
/**
* Retrieves the last known location and returns it to the specified Javascript function
*
* @param callback Javascript function that will be invoked with the last known location
*/
@Kroll.method
public void getCurrentPosition(KrollFunction callback)
{
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing");
return;
}
if (callback != null) {
Location latestKnownLocation = tiLocation.getLastKnownLocation();
if (latestKnownLocation != null) {
callback.call(this.getKrollObject(), new Object[] {
buildLocationEvent(latestKnownLocation, tiLocation.locationManager.getProvider(latestKnownLocation.getProvider()))
});
} else {
Log.e(TAG, "Unable to get current position, location is null");
callback.call(this.getKrollObject(), new Object[] {
buildLocationErrorEvent(TiLocation.ERR_POSITION_UNAVAILABLE, "location is currently unavailable.")
});
}
}
}
/**
* Converts the specified address to coordinates and returns the value to the specified
* Javascript function
*
* @param address address to be converted
* @param callback Javascript function that will be invoked with the coordinates
* for the specified address if available
*/
@Kroll.method
public void forwardGeocoder(String address, KrollFunction callback)
{
tiLocation.forwardGeocode(address, createGeocodeResponseHandler(callback));
}
/**
* Converts the specified latitude and longitude to a human readable address and returns
* the value to the specified Javascript function
*
* @param latitude latitude to be used in looking up the associated address
* @param longitude longitude to be used in looking up the associated address
* @param callback Javascript function that will be invoked with the address
* for the specified latitude and longitude if available
*/
@Kroll.method
public void reverseGeocoder(double latitude, double longitude, KrollFunction callback)
{
tiLocation.reverseGeocode(latitude, longitude, createGeocodeResponseHandler(callback));
}
/**
* Convenience method for creating a response handler that is used when doing a
* geocode lookup.
*
* @param callback Javascript function that the response handler will invoke
* once the geocode response is ready
* @return the geocode response handler
*/
private GeocodeResponseHandler createGeocodeResponseHandler(final KrollFunction callback)
{
final GeolocationModule geolocationModule = this;
return new GeocodeResponseHandler() {
@Override
public void handleGeocodeResponse(KrollDict geocodeResponse)
{
geocodeResponse.put(TiC.EVENT_PROPERTY_SOURCE, geolocationModule);
callback.call(getKrollObject(), new Object[] { geocodeResponse });
}
};
}
/**
* Called to determine if the specified location is "better" than the current location.
* This is determined by comparing the new location to the current location according
* to the location rules (if any are set) for the current behavior mode. If no rules
* are set for the current behavior mode, the new location is always accepted.
*
* @param newLocation location to evaluate
* @return <code>true</code> if the location has been deemed better than
* the current location based on the existing rules set for the
* current behavior mode, <code>false</code> if not
*/
private boolean shouldUseUpdate(Location newLocation)
{
boolean passed = false;
if (getManualMode()) {
if (androidModule.manualLocationRules.size() > 0) {
for(LocationRuleProxy rule : androidModule.manualLocationRules) {
if (rule.check(currentLocation, newLocation)) {
passed = true;
break;
}
}
} else {
passed = true; // no rules set, always accept
}
} else if (!legacyModeActive) {
for(LocationRuleProxy rule : simpleLocationRules) {
if (rule.check(currentLocation, newLocation)) {
passed = true;
break;
}
}
// TODO remove this block when legacy mode is removed
} else {
// the legacy mode will fall here, don't filter the results
passed = true;
}
return passed;
}
/**
* Convenience method used to package a location from a location provider into a
* consumable form for the Titanium developer before it is fire back to Javascript.
*
* @param location location that needs to be packaged into consumable form
* @param locationProvider location provider that provided the location update
* @return map of property names and values that contain information
* pulled from the specified location
*/
private KrollDict buildLocationEvent(Location location, LocationProvider locationProvider)
{
KrollDict coordinates = new KrollDict();
coordinates.put(TiC.PROPERTY_LATITUDE, location.getLatitude());
coordinates.put(TiC.PROPERTY_LONGITUDE, location.getLongitude());
coordinates.put(TiC.PROPERTY_ALTITUDE, location.getAltitude());
coordinates.put(TiC.PROPERTY_ACCURACY, location.getAccuracy());
coordinates.put(TiC.PROPERTY_ALTITUDE_ACCURACY, null); // Not provided
coordinates.put(TiC.PROPERTY_HEADING, location.getBearing());
coordinates.put(TiC.PROPERTY_SPEED, location.getSpeed());
coordinates.put(TiC.PROPERTY_TIMESTAMP, location.getTime());
KrollDict event = new KrollDict();
event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null);
event.put(TiC.PROPERTY_COORDS, coordinates);
if (locationProvider != null) {
KrollDict provider = new KrollDict();
provider.put(TiC.PROPERTY_NAME, locationProvider.getName());
provider.put(TiC.PROPERTY_ACCURACY, locationProvider.getAccuracy());
provider.put(TiC.PROPERTY_POWER, locationProvider.getPowerRequirement());
event.put(TiC.PROPERTY_PROVIDER, provider);
}
return event;
}
/**
* Convenience method used to package a error into a consumable form
* for the Titanium developer before it is fired back to Javascript.
*
* @param code Error code identifying the error
* @param msg Error message describing the event
* @return map of property names and values that contain information
* regarding the error
*/
private KrollDict buildLocationErrorEvent(int code, String msg)
{
KrollDict d = new KrollDict(3);
d.putCodeAndMessage(code, msg);
return d;
}
@Override
public String getApiName()
{
return "Ti.Geolocation";
}
@Override
public void onDestroy(Activity activity) {
//clean up event listeners
if (compassListenersRegistered) {
tiCompass.unregisterListener();
compassListenersRegistered = false;
}
disableLocationProviders();
super.onDestroy(activity);
}
}
|
Java
|
package repomodel
import (
"github.com/kopia/kopia/repo/content"
"github.com/kopia/kopia/repo/manifest"
)
// RepositorySession models the behavior of a single session in an repository.
type RepositorySession struct {
OpenRepo *OpenRepository
WrittenContents ContentSet
WrittenManifests ManifestSet
}
// WriteContent adds the provided content ID to the model.
func (s *RepositorySession) WriteContent(cid content.ID) {
s.WrittenContents.Add(cid)
}
// WriteManifest adds the provided manifest ID to the model.
func (s *RepositorySession) WriteManifest(mid manifest.ID) {
s.WrittenManifests.Add(mid)
}
// Refresh refreshes the set of committed contents and manifest from repositor.
func (s *RepositorySession) Refresh() {
s.OpenRepo.Refresh()
}
// Flush flushes the changes written in this RepositorySession and makes them available
// to other RepositoryData model.
func (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) {
s.OpenRepo.mu.Lock()
defer s.OpenRepo.mu.Unlock()
// data flushed is visible to other sessions in the same open repository.
s.OpenRepo.Contents.Add(wc.ids...)
s.OpenRepo.Manifests.Add(wm.ids...)
// data flushed is visible to other sessions in other open repositories.
s.OpenRepo.RepoData.Contents.Add(wc.ids...)
s.OpenRepo.RepoData.Manifests.Add(wm.ids...)
s.WrittenContents.RemoveAll(wc.ids...)
s.WrittenManifests.RemoveAll(wm.ids...)
}
|
Java
|
using EPiServer.Core;
namespace EPiServer.SocialAlloy.Web.Social.Models
{
/// <summary>
/// The LikeButtonBlockViewModel class represents the model that will be used to
/// provide data to the Like button block frontend view.
/// </summary>
public class LikeButtonBlockViewModel
{
/// <summary>
/// Parameterless constructor
/// </summary>
public LikeButtonBlockViewModel()
{
}
/// <summary>
/// Gets or sets the current page link.
/// </summary>
public PageReference PageLink { get; set; }
/// <summary>
/// Gets or sets the total number of Liked ratings found for the current page.
/// </summary>
public long TotalCount { get; set; }
/// <summary>
/// Gets or sets the existing Liked rating, if any, submitted by current user for the current page.
/// </summary>
public int? CurrentRating { get; set; }
}
}
|
Java
|
# Adactylus ellipticus (J.J.Sm.) Cretz. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
package org.xmlcml.ami.visitor;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.xmlcml.ami.util.AMIUtil;
import org.xmlcml.ami.visitable.VisitableInput;
/** manages the output.
*
* Decides whether to create files or directories. May map the structure onto the input structure.
*
* @author pm286
*
*/
public class VisitorOutput {
private static final Logger LOG = Logger.getLogger(VisitorOutput.class);
private static final String DEFAULT_OUTPUT_LOCATION = "target/";
private static final String DEFAULT_BASENAME = "dummy";
private static final String DEFAULT_OUTPUT_SUFFIX = ".xml";
private String outputLocation;
// private VisitableInput visitableInput;
private List<VisitableInput> visitableInputList;
private String extension;
private boolean isDirectory;
private File outputDirectory;
/** reads outputLocation and ducktypes the type (File, Directory, etc.).
*
* @param outputLocation
*/
public VisitorOutput(String outputLocation) {
setDefaults();
this.outputLocation = outputLocation;
generateOutputDirectoryName();
}
/** this creates a default outputLocation
*
*/
public VisitorOutput() {
setDefaults();
}
private void setDefaults() {
outputLocation = DEFAULT_OUTPUT_LOCATION;
extension = DEFAULT_OUTPUT_SUFFIX;
outputDirectory = new File(DEFAULT_OUTPUT_LOCATION);
}
/** not yet used
*
* @param visitableInput
*/
public void setVisitableInputList(List<VisitableInput> visitableInputList) {
this.visitableInputList = visitableInputList;
}
private void generateOutputDirectoryName() {
if (outputLocation.startsWith(AMIUtil.HTTP)) {
throw new RuntimeException("Cannot output to URL: "+outputLocation);
}
if (outputLocation.startsWith(AMIUtil.DOI)) {
throw new RuntimeException("Cannot output to DOI: "+outputLocation);
}
if (outputLocation == null) {
LOG.info("No explicit output location");
} else {
outputLocation = FilenameUtils.normalize(new File(outputLocation).getAbsolutePath());
extension = FilenameUtils.getExtension(outputLocation);
isDirectory = AMIUtil.endsWithSeparator(outputLocation) || extension == null || extension.equals("");
outputDirectory = new File(outputLocation);
}
}
protected String getOutputLocation() {
return outputLocation;
}
protected String getExtension() {
return extension;
}
protected boolean isDirectory() {
return isDirectory;
}
public File getOutputDirectoryFile() {
if (outputDirectory != null) {
LOG.trace("outputDirectory: "+outputDirectory);
if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
LOG.info("existing file is not a directory: "+outputDirectory);
} else {
ifNotEndsWithSlashUseParentAsOutputDirectory();
outputDirectory.mkdirs();
String baseName = (visitableInputList == null || visitableInputList.size() == 0) ? DEFAULT_BASENAME
: visitableInputList.get(0).getBaseName();
LOG.trace("basename "+baseName);
outputDirectory = new File(outputDirectory, baseName+"."+extension);
}
} else {
throw new RuntimeException("Null output directory");
}
return outputDirectory;
}
private void ifNotEndsWithSlashUseParentAsOutputDirectory() {
if (!outputDirectory.toString().endsWith("/")) {
File parent = outputDirectory.getParentFile();
outputDirectory = (parent == null) ? outputDirectory : parent;
}
}
public void setExtension(String extension) {
this.extension = extension;
}
}
|
Java
|
/*
Copyright 2006 Jerry Huxtable
Copyright 2009 Martin Davis
Copyright 2012 Antoine Gourlay
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.jproj;
import java.text.DecimalFormat;
/**
* Stores a the coordinates for a position
* defined relative to some {@link CoordinateReferenceSystem}.
* The coordinate is defined via X, Y, and optional Z ordinates.
* Provides utility methods for comparing the ordinates of two positions and
* for creating positions from Strings/storing positions as strings.
* <p>
* The primary use of this class is to represent coordinate
* values which are to be transformed
* by a {@link CoordinateTransform}.
*/
public class ProjCoordinate {
private static final String DECIMAL_FORMAT_PATTERN = "0.0###############";
// a DecimalFormat is not ThreadSafe, hence the ThreadLocal variable.
private static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT = new ThreadLocal<DecimalFormat>() {
@Override
protected DecimalFormat initialValue() {
return new DecimalFormat(DECIMAL_FORMAT_PATTERN);
}
};
/**
* The X ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double x;
/**
* The Y ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double y;
/**
* The Z ordinate for this point.
* If this variable has the value <tt>Double.NaN</tt>
* then this coordinate does not have a Z value.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double z;
/**
* Creates a ProjCoordinate with default ordinate values.
*
*/
public ProjCoordinate() {
this(0.0, 0.0);
}
/**
* Creates a ProjCoordinate with values copied from the given coordinate object.
* @param pt a ProjCoordinate to copy
*/
public ProjCoordinate(ProjCoordinate pt) {
this(pt.x, pt.y, pt.z);
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing),
* and the third double parameter is the z ordinate (elevation or height).
*
* Valid values should be passed for all three (3) double parameters. If
* you want to create a horizontal-only point without a valid Z value, use
* the constructor defined in this class that only accepts two (2) double
* parameters.
*
* @param argX
* @param argY
* @param argZ
* @see #ProjCoordinate(double argX, double argY)
*/
public ProjCoordinate(double argX, double argY, double argZ) {
this.x = argX;
this.y = argY;
this.z = argZ;
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing).
* This constructor is used to create a "2D" point, so the Z ordinate
* is automatically set to Double.NaN.
* @param argX
* @param argY
*/
public ProjCoordinate(double argX, double argY) {
this.x = argX;
this.y = argY;
this.z = Double.NaN;
}
/**
* Create a ProjCoordinate by parsing a String in the same format as returned
* by the toString method defined by this class.
*
* @param argToParse the string to parse
*/
public ProjCoordinate(String argToParse) {
// Make sure the String starts with "ProjCoordinate: ".
if (!argToParse.startsWith("ProjCoordinate: ")) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// 15 characters should cut out "ProjCoordinate: ".
String chomped = argToParse.substring(16);
// Get rid of the starting and ending square brackets.
String withoutFrontBracket = chomped.substring(1);
// Calc the position of the last bracket.
int length = withoutFrontBracket.length();
int positionOfCharBeforeLast = length - 2;
String withoutBackBracket = withoutFrontBracket.substring(0,
positionOfCharBeforeLast);
// We should be left with just the ordinate values as strings,
// separated by spaces. Split them into an array of Strings.
String[] parts = withoutBackBracket.split(" ");
// Get number of elements in Array. There should be two (2) elements
// or three (3) elements.
// If we don't have an array with two (2) or three (3) elements,
// then we need to throw an exception.
if (parts.length != 2 && parts.length != 3) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// Convert strings to doubles.
this.x = "NaN".equals(parts[0]) ? Double.NaN : Double.parseDouble(parts[0]);
this.y = "NaN".equals(parts[1]) ? Double.NaN : Double.parseDouble(parts[1]);
// You might not always have a Z ordinate. If you do, set it.
if (parts.length == 3) {
this.z = "NaN".equals(parts[2]) ? Double.NaN : Double.parseDouble(parts[2]);
} else {
this.z = Double.NaN;
}
}
/**
* Sets the value of this coordinate to
* be equal to the given coordinate's ordinates.
*
* @param p the coordinate to copy
*/
public void setValue(ProjCoordinate p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
}
/**
* Returns a boolean indicating if the X ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the X ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areXOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the x ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.x - this.x <= argTolerance;
}
/**
* Returns a boolean indicating if the Y ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Y ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areYOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the y ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.y - this.y <= argTolerance;
}
/**
* Returns a boolean indicating if the Z ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Z ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
*
* If both Z ordinate values are Double.NaN this method will return
* true. If one Z ordinate value is a valid double value and one is
* Double.Nan, this method will return false.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areZOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// We have to handle Double.NaN values here, because not every
// ProjCoordinate will have a valid Z Value.
if (Double.isNaN(z)) {
return Double.isNaN(argToCompare.z);
// if true, both the z ordinate values are Double.Nan.
// else, We've got one z ordinate with a valid value and one with
// a Double.NaN value.
} // We have a valid z ordinate value in this ProjCoordinate object.
else {
if (Double.isNaN(argToCompare.z)) {
// We've got one z ordinate with a valid value and one with
// a Double.NaN value. Return false.
return false;
}
// If we get to this point in the method execution, we have to
// z ordinates with valid values, and we need to do a regular
// comparison. This is done in the remainder of the method.
}
// Subtract the z ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.z - this.z <= argTolerance;
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>ProjCoordinate[X Y Z]</tt>.
* <p>
* Example:
* <pre>
* ProjCoordinate[6241.11 5218.25 12.3]
* </pre>
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ProjCoordinate[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(x);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(y);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(z);
}
builder.append("]");
return builder.toString();
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>[X Y]</tt>
* or <tt>[X, Y, Z]</tt>.
* Z is not displayed if it is NaN.
* <p>
* Example:
* <pre>
* [6241.11, 5218.25, 12.3]
* </pre>
* @return
*/
public String toShortString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(x));
}
builder.append(", ");
if (Double.isNaN(y)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(y));
}
if (!Double.isNaN(z)) {
builder.append(", ");
builder.append(this.z);
}
builder.append("]");
return builder.toString();
}
public boolean hasValidZOrdinate() {
return !Double.isNaN(z);
}
/**
* Indicates if this ProjCoordinate has valid X ordinate and Y ordinate
* values. Values are considered invalid if they are Double.NaN or
* positive/negative infinity.
* @return
*/
public boolean hasValidXandYOrdinates() {
return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y) && !Double.isInfinite(y);
}
}
|
Java
|
package interviews;
public class Yahoo {
}
Run Length Encoding for byte array
Input byte array [10, 10, 10, 255, 255, 0, 10] ==> output byte array [3, 10, 2, 255, 1, 0, 1, 10]
Class ByteArrayEncodeDecode {
public byte[] encodeByteArray(byte[] input) {
int n = input.length;
if (n == 0) return new byte[];
Arraylist<Byte> out = Arraylist<Byte>();
byte prevByte = input[0];
byte prevCount = 1;
for (int i = 1; i < n; i++) {
if(prevByte == input[i] && prevCount != 255){ //
prevCount++;
} else {
out.add(prevCount);
out.add(prevByte);
prevByte = input[i];
prevCount = 1;
}
}
out.add(prevCount);
out.add(prevByte);
return out.toArray();
}
public static void main() {
}
}
// [] ==> []
// [1] ==> [1, 1]
// [1, 1, 1, 2, 2, 3] ==> [3, 1, 2, 2, 1, 3]
// [1 ... 300.....1] ==> [255, 1, 45, 1]
|
Java
|
/*******************************************************************\
Module: Type Naming for C
Author: Daniel Kroening, kroening@cs.cmu.edu
\*******************************************************************/
#include <ctype.h>
#include <i2string.h>
#include <std_types.h>
#include "type2name.h"
/*******************************************************************\
Function: type2name
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string type2name(const typet &type)
{
std::string result;
if(type.id()=="")
throw "Empty type encountered.";
else if(type.id()=="empty")
result+="V";
else if(type.id()=="signedbv")
result+="S" + type.width().as_string();
else if(type.id()=="unsignedbv")
result+="U" + type.width().as_string();
else if(type.is_bool())
result+="B";
else if(type.id()=="integer")
result+="I";
else if(type.id()=="real")
result+="R";
else if(type.id()=="complex")
result+="C";
else if(type.id()=="float")
result+="F";
else if(type.id()=="floatbv")
result+="F" + type.width().as_string();
else if(type.id()=="fixed")
result+="X";
else if(type.id()=="fixedbv")
result+="X" + type.width().as_string();
else if(type.id()=="natural")
result+="N";
else if(type.id()=="pointer")
result+="*";
else if(type.id()=="reference")
result+="&";
else if(type.is_code())
{
const code_typet &t = to_code_type(type);
const code_typet::argumentst arguments = t.arguments();
result+="P(";
for (code_typet::argumentst::const_iterator it = arguments.begin();
it!=arguments.end();
it++)
{
result+=type2name(it->type());
result+="'" + it->get_identifier().as_string() + "'|";
}
result.resize(result.size()-1);
result+=")";
}
else if(type.is_array())
{
const array_typet &t = to_array_type(type);
result+="ARR" + t.size().value().as_string();
}
else if(type.id()=="incomplete_array")
{
result+="ARR?";
}
else if(type.id()=="symbol")
{
result+="SYM#" + type.identifier().as_string() + "#";
}
else if(type.id()=="struct" ||
type.id()=="union")
{
if(type.id()=="struct") result +="ST";
if(type.id()=="union") result +="UN";
const struct_typet &t = to_struct_type(type);
const struct_typet::componentst &components = t.components();
result+="[";
for(struct_typet::componentst::const_iterator it = components.begin();
it!=components.end();
it++)
{
result+=type2name(it->type());
result+="'" + it->name().as_string() + "'|";
}
result.resize(result.size()-1);
result+="]";
}
else if(type.id()=="incomplete_struct")
result +="ST?";
else if(type.id()=="incomplete_union")
result +="UN?";
else if(type.id()=="c_enum")
result +="EN" + type.width().as_string();
else if(type.id()=="incomplete_c_enum")
result +="EN?";
else if(type.id()=="c_bitfield")
{
result+="BF" + type.size().as_string();
}
else
{
throw (std::string("Unknown type '") +
type.id().as_string() +
"' encountered.");
}
if(type.has_subtype())
{
result+="{";
result+=type2name(type.subtype());
result+="}";
}
if(type.has_subtypes())
{
result+="$";
forall_subtypes(it, type)
{
result+=type2name(*it);
result+="|";
}
result.resize(result.size()-1);
result+="$";
}
return result;
}
|
Java
|
# Hemimycena guanacastensis Singer SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Fieldiana, Bot. 21: 68 (1989)
#### Original name
Hemimycena guanacastensis Singer
### Remarks
null
|
Java
|
using System;
namespace ProSecuritiesTrading.MOEX.FIX.Base.Field
{
public class PartyID
{
public const int Tag = 448;
public static readonly byte[] TagBytes;
static PartyID()
{
TagBytes = new byte[3];
TagBytes[0] = 52;
TagBytes[1] = 52;
TagBytes[2] = 56;
}
}
}
|
Java
|
/*
* Copyright 2013-2017 Grzegorz Ligas <ligasgr@gmail.com> and other contributors
* (see the CONTRIBUTORS file).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a generated file. Not intended for manual editing.
package org.intellij.xquery.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface XQueryContextItemDecl extends XQueryPsiElement {
@Nullable
XQueryItemType getItemType();
@Nullable
XQuerySeparator getSeparator();
@Nullable
XQueryVarDefaultValue getVarDefaultValue();
@Nullable
XQueryVarValue getVarValue();
}
|
Java
|
using GoBuddies.Server.Data;
using GoBuddies.Server.Data.DbModels;
using GoBuddies.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.Swagger.Model;
using System;
using System.IO;
namespace GoBuddies.Server.WebApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
//builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
////services.AddApplicationInsightsTelemetry(Configuration);
// add ef
services.AddDbContext<ApplicationDbContext>(options => options.UseInMemoryDatabase());
// add swagger
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Geo Search API",
Description = "A simple api to search using geo location in Elasticsearch",
TermsOfService = "None"
});
string pathToDoc = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GoBuddies.Server.WebApi.XML");
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
// config identity
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie";
options.Cookies.ApplicationCookie.CookieName = "Interop";
options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\Identities"));
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
////app.UseApplicationInsightsRequestTelemetry();
////app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}");
});
app.UseIdentity();
app.UseOData("odata");
app.UseSwagger();
app.UseSwaggerUi();
}
}
}
|
Java
|
/*
* Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences.
*
* This file is part of Duckling 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 net.duckling.vmt.domain;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
public class HttpGet {
private static final Logger LOG=Logger.getLogger(HttpGet.class);
private String path;
private String encode="UTF-8";
public HttpGet(String url,String encode){
this.path=url;
this.encode=encode;
}
public HttpGet(String url){
this.path=url;
}
public String connect(){
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
LOG.error(e.getMessage()+",can't touch this url="+path, e);
return null;
}
try (InputStream ins = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins, encode));) {
String line;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
return null;
}
}
}
|
Java
|
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.psi.impl.symbols;
import com.intellij.lang.ASTNode;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaParameter;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaUpvalueIdentifier;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 1/26/11
* Time: 9:23 PM
*/
public class LuaUpvalueIdentifierImpl extends LuaLocalIdentifierImpl implements LuaUpvalueIdentifier {
public LuaUpvalueIdentifierImpl(ASTNode node) {
super(node);
}
@Override
public boolean isSameKind(LuaSymbol symbol) {
return symbol instanceof LuaLocalDeclarationImpl || symbol instanceof LuaParameter;
}
@Override
public String toString() {
return "Upvalue: " + getText();
}
}
|
Java
|
<?php
namespace ContainerFelbUiK;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class getForm_TypeExtension_Form_ValidatorService extends App_KernelDevDebugContainer
{
/**
* Gets the private 'form.type_extension.form.validator' shared service.
*
* @return \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension
*/
public static function do($container, $lazyLoad = true)
{
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/FormTypeExtensionInterface.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/AbstractTypeExtension.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/BaseValidatorExtension.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/FormTypeValidatorExtension.php';
return $container->privates['form.type_extension.form.validator'] = new \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension(($container->services['validator'] ?? $container->getValidatorService()));
}
}
|
Java
|
# Trachycaryon hookeri var. hookeri F.Muell. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Sphaeria corticola Fuckel, 1870 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Jb. nassau. Ver. Naturk. 23-24: (1870)
#### Original name
Sphaeria corticola Fuckel, 1870
### Remarks
null
|
Java
|
# Hutchinsia stricta (Roth) Lyngbye SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Issatchenkia Kudrjanzev GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bot. Mater. Otd. Sporov. Rast. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 13: 143 (1960)
#### Original name
Issatchenkia Kudrjanzev
### Remarks
null
|
Java
|
# Alpinia corneri (Holttum) R.M.Sm. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Cenolophon corneri Holttum
### Remarks
null
|
Java
|
package com.buschmais.xo.neo4j.test.id;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collection;
import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.bootstrap.XOUnit;
import com.buschmais.xo.neo4j.test.AbstractNeo4JXOManagerIT;
import com.buschmais.xo.neo4j.test.id.composite.A;
import com.buschmais.xo.neo4j.test.id.composite.A2B;
import com.buschmais.xo.neo4j.test.id.composite.B;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class EqualsHashcodeIT extends AbstractNeo4JXOManagerIT {
public EqualsHashcodeIT(XOUnit xoUnit) {
super(xoUnit);
}
@Parameterized.Parameters
public static Collection<Object[]> getXOUnits() {
return xoUnits(A.class, B.class, A2B.class);
}
@Test
public void equalsHashcode() {
XOManager xoManager = getXOManager();
xoManager.currentTransaction().begin();
A a = xoManager.create(A.class);
int aHashCode = a.hashCode();
B b = xoManager.create(B.class);
int bHashCode = b.hashCode();
A2B a2b = xoManager.create(a, A2B.class, b);
int a2bHashCode = a2b.hashCode();
xoManager.currentTransaction().commit();
xoManager.currentTransaction().begin();
assertThat(a.equals(a), equalTo(true));
assertThat(b.equals(b), equalTo(true));
assertThat(a2b.equals(a2b), equalTo(true));
assertThat(a.hashCode(), equalTo(aHashCode));
assertThat(b.hashCode(), equalTo(bHashCode));
assertThat(a2b.hashCode(), equalTo(a2bHashCode));
xoManager.currentTransaction().commit();
}
}
|
Java
|
package com.tle.configmanager;
import com.dytech.gui.ComponentHelper;
import com.thoughtworks.xstream.XStream;
import com.tle.common.Check;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.io.FileUtils;
// Author: Andrew Gibb
@SuppressWarnings({"serial", "nls"})
public class ConfigLauncherGUI extends JFrame implements ActionListener {
public static final String MANDATORY_CONFIG = "mandatory-config.properties";
public static final String OPTIONAL_CONFIG = "optional-config.properties";
public static final String HIBERNATE_CONFIG = "hibernate.properties";
public static final String LOGGING_CONFIG = "learningedge-log4j.properties";
public static final String IMAGEMAGICK_CONFIG =
"plugins/com.tle.core.imagemagick/config.properties.unresolved";
public static final String HIKARI_CONFIG = "hikari.properties";
private final String TITLE = "TLE Configuration Manager";
private final String PATH = "./configs/";
private final String ORACLE = "oracle";
private final String POSTGRESQL = "postgresql";
private final String MSSQL = "ms sql";
private final String source;
private final String destination;
private JLabel lblConfig;
private JComboBox<ConfigProfile> cmbConfigs;
private JButton btnNew, btnEdit, btnApply, btnDelete;
private JSeparator sep;
private List<ConfigProfile> configs;
public ConfigLauncherGUI(String source, String destination) {
setTitle(TITLE);
setupGUI();
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.source = source;
this.destination = destination;
// Set a minimum width...leave the height to the pack...
setMinimumSize(new Dimension(300, 0));
pack();
ComponentHelper.centreOnScreen(this);
// Updated combo box containing profiles
updateConfigs();
}
// Sets up the GUI for managing/loading the configuration profiles
private void setupGUI() {
Container contents = getContentPane();
contents.setLayout(new MigLayout("wrap 3", "[grow][grow][grow]"));
configs = new ArrayList<ConfigProfile>();
lblConfig = new JLabel("Configurations: ");
cmbConfigs = new JComboBox<ConfigProfile>();
btnNew = new JButton("New");
btnNew.addActionListener(this);
btnApply = new JButton("Apply Configuration");
btnApply.addActionListener(this);
btnEdit = new JButton("Edit");
btnEdit.addActionListener(this);
sep = new JSeparator();
btnDelete = new JButton("Delete");
btnDelete.addActionListener(this);
contents.add(lblConfig, "growx, spanx 3");
contents.add(cmbConfigs, "growx, spanx 3");
contents.add(btnNew, "growx, center");
contents.add(btnEdit, "growx, center");
contents.add(btnDelete, "growx, center");
contents.add(sep, "growx, spanx 3");
contents.add(btnApply, "center, growx, spanx 3");
}
// Updates the available configuration profiles
public void updateConfigs() {
File srcDir = new File(PATH);
File[] configFiles = srcDir.listFiles();
Reader rdr;
cmbConfigs.removeAllItems();
configs.clear();
if (configFiles != null) {
for (File f : configFiles) {
if (f.isFile()) {
XStream xstream = new XStream();
try {
rdr = new BufferedReader(new FileReader(f));
ConfigProfile prof = (ConfigProfile) xstream.fromXML(rdr);
configs.add(prof);
rdr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Collections.sort(
configs,
new Comparator<ConfigProfile>() {
@Override
public int compare(ConfigProfile o1, ConfigProfile o2) {
return o1.getProfName().compareToIgnoreCase(o2.getProfName());
}
});
for (ConfigProfile prof : configs) {
cmbConfigs.addItem(prof);
}
}
if (configs.isEmpty()) {
btnEdit.setEnabled(false);
btnApply.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnApply.setEnabled(true);
btnDelete.setEnabled(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNew) {
addProfile();
} else if (e.getSource() == btnEdit) {
editProfile();
} else if (e.getSource() == btnDelete) {
deleteProfile();
} else if (e.getSource() == btnApply) {
try {
loadProfile();
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,
"Error loading configuration: \n" + ex.getMessage(),
"Load Failed",
JOptionPane.ERROR_MESSAGE);
}
}
}
// Adds a new profile which is either a clone of an existing profile or is
// blank
private void addProfile() {
ConfigEditorGUI confEd = null;
if (configs != null && cmbConfigs.getSelectedItem() != null) {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
int result =
JOptionPane.showConfirmDialog(
null,
"Do you want to clone the currently selected configuration?: "
+ selectedProf.getProfName(),
"Clone Confirmation",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
confEd = new ConfigEditorGUI(selectedProf, "copy");
} else {
confEd = new ConfigEditorGUI();
}
} else {
confEd = new ConfigEditorGUI();
}
confEd.setModal(true);
confEd.setVisible(true);
if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) {
updateConfigs();
}
}
// Edits and existing profile
private void editProfile() {
int index = cmbConfigs.getSelectedIndex();
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
ConfigEditorGUI confEd = new ConfigEditorGUI(selectedProf);
confEd.setModal(true);
confEd.setVisible(true);
if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) {
updateConfigs();
cmbConfigs.setSelectedIndex(index);
}
}
// Deletes a configuration profile
private void deleteProfile() {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
File toDel = new File(PATH + selectedProf.getProfName() + ".xml");
int result =
JOptionPane.showConfirmDialog(
null,
"Are you sure you want to delete this configuration?: " + selectedProf.getProfName(),
"Delete Confirmation",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
boolean success = toDel.delete();
if (!success) {
JOptionPane.showMessageDialog(
null,
"Unable to delete configuration: " + selectedProf.getProfName(),
"Delete Failed",
JOptionPane.ERROR_MESSAGE);
}
}
updateConfigs();
}
// Loads a profile (SUPER HACKISH)
private void loadProfile() throws FileNotFoundException, IOException, ConfigurationException {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
File srcDir = new File(source);
// Remove Current Configuration Files
File destDir = new File(destination);
FileUtils.deleteDirectory(destDir);
// Create Destination
destDir.mkdir();
// Copy Required Files (Database Specific)
boolean oracleSelected = selectedProf.getDbtype().equalsIgnoreCase(ORACLE);
if (oracleSelected) {
org.apache.commons.io.FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.oracle"),
new File(destDir + "/hibernate.properties"));
} else if (selectedProf.getDbtype().equalsIgnoreCase(POSTGRESQL)) {
FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.postgresql"),
new File(destDir + "/hibernate.properties"));
} else if (selectedProf.getDbtype().equalsIgnoreCase(MSSQL)) {
FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.sqlserver"),
new File(destDir + "/hibernate.properties"));
}
// Mandatory / Optional / Logging
FileUtils.copyFile(
new File(srcDir + "/mandatory-config.properties"),
new File(destDir + "/mandatory-config.properties"));
FileUtils.copyFile(
new File(srcDir + "/optional-config.properties"),
new File(destDir + "/optional-config.properties"));
// Copy custom development logging file
FileUtils.copyFile(
new File("./learningedge-log4j.properties"),
new File(destDir + "/learningedge-log4j.properties"));
// Other Miscellaneous Files
FileUtils.copyFile(
new File(srcDir + "/en-stopWords.txt"), new File(destDir + "/en-stopWords.txt"));
FileUtils.copyFile(
new File(srcDir + "/" + HIKARI_CONFIG), new File(destDir + "/" + HIKARI_CONFIG));
// Plugins Folder
FileUtils.copyDirectoryToDirectory(new File(srcDir + "/plugins"), destDir);
// Edit Hibernate Properties
String hibProp = readFile(destination + "/" + HIBERNATE_CONFIG);
hibProp = hibProp.replace("${datasource/host}", selectedProf.getHost());
hibProp = hibProp.replace("${datasource/port}", selectedProf.getPort());
hibProp = hibProp.replace("${datasource/database}", selectedProf.getDatabase());
hibProp = hibProp.replace("${datasource/username}", selectedProf.getUsername());
hibProp = hibProp.replace("${datasource/password}", selectedProf.getPassword());
hibProp =
hibProp.replace(
"${datasource/schema}",
oracleSelected ? "hibernate.default_schema = " + selectedProf.getUsername() : "");
writeFile(destination + "/hibernate.properties", hibProp);
// Edit Mandatory Properties
PropertyEditor mandProps = new PropertyEditor();
mandProps.load(new File(destination + "/" + MANDATORY_CONFIG));
String http = selectedProf.getHttp();
String portFromUrl = selectedProf.getAdminurl().split(":")[1];
mandProps.setProperty(
"http.port",
!Check.isEmpty(http) ? http : !Check.isEmpty(portFromUrl) ? portFromUrl : "80");
String https = selectedProf.getHttps();
if (!Check.isEmpty(https)) {
mandProps.setProperty("https.port", https);
}
String ajp = selectedProf.getAjp();
if (!Check.isEmpty(https)) {
mandProps.setProperty("ajp.port", ajp);
}
mandProps.setProperty("filestore.root", selectedProf.getFilestore());
mandProps.setProperty("java.home", selectedProf.getJavahome());
mandProps.setProperty("admin.url", selectedProf.getAdminurl());
mandProps.setProperty("freetext.index.location", selectedProf.getFreetext());
mandProps.setProperty("freetext.stopwords.file", selectedProf.getStopwords());
String reporting = selectedProf.getReporting();
if (!Check.isEmpty(reporting)) {
mandProps.setProperty("reporting.workspace.location", reporting);
}
mandProps.setProperty("plugins.location", selectedProf.getPlugins());
mandProps.save(new File(destination + "/" + MANDATORY_CONFIG));
// Edit Optional Properties
String optProp = readFile(destination + "/" + OPTIONAL_CONFIG);
if (selectedProf.isDevinst()) {
optProp =
optProp.replace(
"#conversionService.disableConversion = false",
"conversionService.disableConversion = true");
optProp =
optProp.replace(
"conversionService.conversionServicePath = ${install.path#t\\/}/conversion/conversion-service.jar",
"#conversionService.conversionServicePath =");
optProp =
optProp.replace("#pluginPathResolver.wrappedClass", "pluginPathResolver.wrappedClass");
} else {
optProp =
optProp.replace(
"${install.path#t\\/}/conversion/conversion-service.jar",
selectedProf.getConversion());
}
writeFile(destination + "/optional-config.properties", optProp);
// Edit ImageMagik Properties (MORE HAX...)
File imgmgk = new File(destination + "/" + IMAGEMAGICK_CONFIG);
PropertyEditor magickProps = new PropertyEditor();
magickProps.load(imgmgk);
magickProps.setProperty("imageMagick.path", selectedProf.getImagemagick());
magickProps.save(new File((destination + "/" + IMAGEMAGICK_CONFIG).replace(".unresolved", "")));
imgmgk.delete();
JOptionPane.showMessageDialog(
null,
"The configuration: " + selectedProf.getProfName() + " has been successfully loaded.",
"Load Success",
JOptionPane.INFORMATION_MESSAGE);
}
// Reads a file into a string
private String readFile(String path) throws IOException {
StringBuilder contents = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
br.close();
return contents.toString();
}
// Writes a file from String
private void writeFile(String path, String contents) throws IOException {
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(new File(path)));
output.write(contents);
output.close();
}
}
|
Java
|
<?php
final class DrydockLeaseViewController extends DrydockLeaseController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$lease = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withIDs(array($id))
->needUnconsumedCommands(true)
->executeOne();
if (!$lease) {
return new Aphront404Response();
}
$lease_uri = $this->getApplicationURI('lease/'.$lease->getID().'/');
$title = pht('Lease %d', $lease->getID());
$header = id(new PHUIHeaderView())
->setHeader($title);
if ($lease->isReleasing()) {
$header->setStatus('fa-exclamation-triangle', 'red', pht('Releasing'));
}
$actions = $this->buildActionListView($lease);
$properties = $this->buildPropertyListView($lease, $actions);
$pager = new PHUIPagerView();
$pager->setURI(new PhutilURI($lease_uri), 'offset');
$pager->setOffset($request->getInt('offset'));
$logs = id(new DrydockLogQuery())
->setViewer($viewer)
->withLeaseIDs(array($lease->getID()))
->executeWithOffsetPager($pager);
$log_table = id(new DrydockLogListView())
->setUser($viewer)
->setLogs($logs)
->render();
$log_table->appendChild($pager);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($title, $lease_uri);
$locks = $this->buildLocksTab($lease->getPHID());
$commands = $this->buildCommandsTab($lease->getPHID());
$object_box = id(new PHUIObjectBoxView())
->setHeader($header)
->addPropertyList($properties, pht('Properties'))
->addPropertyList($locks, pht('Slot Locks'))
->addPropertyList($commands, pht('Commands'));
$log_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Lease Logs'))
->setTable($log_table);
return $this->buildApplicationPage(
array(
$crumbs,
$object_box,
$log_box,
),
array(
'title' => $title,
));
}
private function buildActionListView(DrydockLease $lease) {
$viewer = $this->getViewer();
$view = id(new PhabricatorActionListView())
->setUser($viewer)
->setObjectURI($this->getRequest()->getRequestURI())
->setObject($lease);
$id = $lease->getID();
$can_release = $lease->canRelease();
if ($lease->isReleasing()) {
$can_release = false;
}
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$lease,
PhabricatorPolicyCapability::CAN_EDIT);
$view->addAction(
id(new PhabricatorActionView())
->setName(pht('Release Lease'))
->setIcon('fa-times')
->setHref($this->getApplicationURI("/lease/{$id}/release/"))
->setWorkflow(true)
->setDisabled(!$can_release || !$can_edit));
return $view;
}
private function buildPropertyListView(
DrydockLease $lease,
PhabricatorActionListView $actions) {
$viewer = $this->getViewer();
$view = new PHUIPropertyListView();
$view->setActionList($actions);
$view->addProperty(
pht('Status'),
DrydockLeaseStatus::getNameForStatus($lease->getStatus()));
$view->addProperty(
pht('Resource Type'),
$lease->getResourceType());
$owner_phid = $lease->getOwnerPHID();
if ($owner_phid) {
$owner_display = $viewer->renderHandle($owner_phid);
} else {
$owner_display = phutil_tag('em', array(), pht('No Owner'));
}
$view->addProperty(pht('Owner'), $owner_display);
$resource_phid = $lease->getResourcePHID();
if ($resource_phid) {
$resource_display = $viewer->renderHandle($resource_phid);
} else {
$resource_display = phutil_tag('em', array(), pht('No Resource'));
}
$view->addProperty(pht('Resource'), $resource_display);
$until = $lease->getUntil();
if ($until) {
$until_display = phabricator_datetime($until, $viewer);
} else {
$until_display = phutil_tag('em', array(), pht('Never'));
}
$view->addProperty(pht('Expires'), $until_display);
$attributes = $lease->getAttributes();
if ($attributes) {
$view->addSectionHeader(
pht('Attributes'), 'fa-list-ul');
foreach ($attributes as $key => $value) {
$view->addProperty($key, $value);
}
}
return $view;
}
}
|
Java
|
# Lecanactis opponens (Nyl.) H. Olivier SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Lecidea opponens Nyl.
### Remarks
null
|
Java
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.Web.Utility.PInvoke.Fusion
{
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
internal interface IAssemblyName
{
[PreserveSig()]
int SetProperty(
int PropertyId,
IntPtr pvProperty,
int cbProperty);
[PreserveSig()]
int GetProperty(
int PropertyId,
IntPtr pvProperty,
ref int pcbProperty);
[PreserveSig()]
int Finalize();
[PreserveSig()]
int GetDisplayName(
StringBuilder pDisplayName,
ref int pccDisplayName,
int displayFlags);
[PreserveSig()]
int Reserved(ref Guid guid,
Object obj1,
Object obj2,
String string1,
Int64 llFlags,
IntPtr pvReserved,
int cbReserved,
out IntPtr ppv);
[PreserveSig()]
int GetName(
ref int pccBuffer,
StringBuilder pwzName);
[PreserveSig()]
int GetVersion(
out int versionHi,
out int versionLow);
[PreserveSig()]
int IsEqual(
IAssemblyName pAsmName,
int cmpFlags);
[PreserveSig()]
int Clone(out IAssemblyName pAsmName);
}// IAssemblyName
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
internal interface IAssemblyCache
{
[PreserveSig()]
int UninstallAssembly(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName,
IntPtr refData,
out int disposition);
[PreserveSig()]
int QueryAssemblyInfo(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName,
ref AssemblyInfo assemblyInfo);
[PreserveSig()]
int Reserved(
int flags,
IntPtr pvReserved,
out object ppAsmItem,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName);
[PreserveSig()]
int Reserved(out object ppAsmScavenger);
[PreserveSig()]
int InstallAssembly(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyFilePath,
IntPtr refData);
}// IAssemblyCache
[StructLayout(LayoutKind.Sequential)]
internal struct AssemblyInfo
{
public int cbAssemblyInfo; // size of this structure for future expansion
public int assemblyFlags;
public long assemblySizeInKB;
[MarshalAs(UnmanagedType.LPWStr)]
public string currentAssemblyPath;
public int cchBuf; // size of path buf.
}
[Flags]
internal enum AssemblyCacheFlags
{
GAC = 2,
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
internal interface IAssemblyEnum
{
[PreserveSig()]
int GetNextAssembly(
IntPtr pvReserved,
out IAssemblyName ppName,
int flags);
[PreserveSig()]
int Reset();
[PreserveSig()]
int Clone(out IAssemblyEnum ppEnum);
}
[Flags]
internal enum AssemblyNameDisplayFlags
{
VERSION = 0x01,
CULTURE = 0x02,
PUBLIC_KEY_TOKEN = 0x04,
PROCESSORARCHITECTURE = 0x20,
RETARGETABLE = 0x80,
// This enum might change in the future to include
// more attributes.
ALL =
VERSION
| CULTURE
| PUBLIC_KEY_TOKEN
| PROCESSORARCHITECTURE
| RETARGETABLE
}
internal enum CreateAssemblyNameObjectFlags
{
CANOF_DEFAULT = 0,
CANOF_PARSE_DISPLAY_NAME = 1,
}
internal static class NativeMethods
{
[DllImport("fusion.dll")]
public static extern int CreateAssemblyCache(
out IAssemblyCache ppAsmCache,
int reserved);
[DllImport("fusion.dll")]
public static extern int CreateAssemblyEnum(
out IAssemblyEnum ppEnum,
IntPtr pUnkReserved,
IAssemblyName pName,
AssemblyCacheFlags flags,
IntPtr pvReserved);
[DllImport("fusion.dll")]
public static extern int CreateAssemblyNameObject(
out IAssemblyName ppAssemblyNameObj,
[MarshalAs(UnmanagedType.LPWStr)]
String szAssemblyName,
CreateAssemblyNameObjectFlags flags,
IntPtr pvReserved);
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Sun Oct 15 22:02:21 CDT 2006 -->
<TITLE>
Uses of Interface org.hibernate.dialect.lock.LockingStrategy (Hibernate API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../jdstyle.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface org.hibernate.dialect.lock.LockingStrategy (Hibernate API Documentation)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="LockingStrategy.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.hibernate.dialect.lock.LockingStrategy</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.dialect"><B>org.hibernate.dialect</B></A></TD>
<TD>
This package abstracts the SQL dialect of the underlying database. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.dialect.lock"><B>org.hibernate.dialect.lock</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.persister.entity"><B>org.hibernate.persister.entity</B></A></TD>
<TD>
This package abstracts persistence mechanisms for
entities, and defines the Hibernate runtime
metamodel. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.dialect"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A> that implement <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/HSQLDialect.ReadUncommittedLockingStrategy.html" title="class in org.hibernate.dialect">HSQLDialect.ReadUncommittedLockingStrategy</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A> that return <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>TimesTenDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/TimesTenDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>RDMSOS2200Dialect.</B><B><A HREF="../../../../../org/hibernate/dialect/RDMSOS2200Dialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>PointbaseDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/PointbaseDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>MckoiDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/MckoiDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>HSQLDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/HSQLDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>FrontBaseDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/FrontBaseDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>Dialect.</B><B><A HREF="../../../../../org/hibernate/dialect/Dialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
Get a strategy instance which knows how to acquire a database-level lock
of the specified mode for this dialect.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.dialect.lock"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/dialect/lock/package-summary.html">org.hibernate.dialect.lock</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/hibernate/dialect/lock/package-summary.html">org.hibernate.dialect.lock</A> that implement <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/lock/SelectLockingStrategy.html" title="class in org.hibernate.dialect.lock">SelectLockingStrategy</A></B></CODE>
<BR>
A locking strategy where the locks are obtained through select statements.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/lock/UpdateLockingStrategy.html" title="class in org.hibernate.dialect.lock">UpdateLockingStrategy</A></B></CODE>
<BR>
A locking strategy where the locks are obtained through update statements.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.persister.entity"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/persister/entity/package-summary.html">org.hibernate.persister.entity</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../../org/hibernate/persister/entity/package-summary.html">org.hibernate.persister.entity</A> that return <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>AbstractEntityPersister.</B><B><A HREF="../../../../../org/hibernate/persister/entity/AbstractEntityPersister.html#generateLocker(org.hibernate.LockMode)">generateLocker</A></B>(<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="LockingStrategy.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
Java
|
# Russula decolorans var. albida A. Blytt VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Russula decolorans var. albida A. Blytt
### Remarks
null
|
Java
|
# Meibomia megaphylla (Zoll.) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Artanthe poeppigii var. glabrior Miq. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Teucrium polium subsp. carthaginense (Lange) O.Bolòs & Vigo SUBSPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Teucrium carthaginense Lange
### Remarks
null
|
Java
|
# Ficus virgata Reinw. ex Blume SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Bijdr. 454. 1825
#### Original name
null
### Remarks
null
|
Java
|
# Scorzonera tau-saghyz Lipsch. & G.G.Bosse SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Trans. rubber & cuttap. Inst. 1:7. 1930 (Trans. rubber & Cuttap. Inst. 4:27. 1931)
#### Original name
null
### Remarks
null
|
Java
|
# Conyza macrorrhiza Sch.Bip. ex A.Rich. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Zanthoxylum L. GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
package com.krealid.starter.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.krealid.starter.R;
import butterknife.ButterKnife;
/**
* Created by Maxime on 26/08/2015.
*/
public class ActuExpendedAdapter extends RecyclerView.Adapter<ActuExpendedAdapter.ViewHolder> {
private String text;
private Context context;
private View view;
public ActuExpendedAdapter(String text, Context context){
this.text = text;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.actu_text, parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String iframeLink;
if(this.text.contains("<iframe")){
String iframeStart = "<iframe src=\"";
String iframeEnd = "\" width=";
int indexToStartIframe = this.text.indexOf(iframeStart);
int indexToEndIframe = (this.text.substring(indexToStartIframe)).indexOf(iframeEnd);
String iframeHeight = "height=\"";
int indexToStartHeightIframe= this.text.indexOf(iframeHeight);
String iframeHeightValue = this.text.substring(indexToStartHeightIframe + iframeHeight.length(),
this.text.indexOf('"', indexToStartHeightIframe + iframeHeight.length()));
iframeLink = this.text.substring(indexToStartIframe + iframeStart.length(),
indexToStartIframe + indexToEndIframe);
String articleText = this.text.substring(0, indexToStartIframe);
holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" +
articleText + "</font>", "text/html; charset=UTF-8", null);
final RelativeLayout layout = new RelativeLayout(this.context);
RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(lprams);
WebView web1 = new WebView(this.context);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setPluginState(WebSettings.PluginState.ON);
web1.loadUrl(iframeLink);
web1.setId(R.id.myWebView);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
Integer.parseInt(iframeHeightValue),
this.context.getResources().getDisplayMetrics());
final RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, height);
layout.addView(web1, webViewParams);
holder.articleContainer.addView(layout);
} else {
holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" +
this.text + "</font>", "text/html; charset=UTF-8", null);
}
}
@Override
public int getItemCount() {
return 1;
}
public void stopVideo(){
ViewHolder holder = new ViewHolder(view);
WebView mWebView = (WebView) holder.articleContainer.findViewById(R.id.myWebView);
if(mWebView != null)
mWebView.loadUrl("about:blank");
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public WebView text;
public LinearLayout articleContainer;
public ViewHolder(View itemView) {
super(itemView);
text = ButterKnife.findById(itemView, R.id.articleContent);
articleContainer = ButterKnife.findById(itemView, R.id.article_container);
}
}
}
|
Java
|
//
// PBObjcWrapper.h
// AppBootstrap
//
// Created by Yaming on 10/31/14.
// Copyright (c) 2014 whosbean.com. All rights reserved.
//
#import <Foundation/Foundation.h>
#ifdef __cplusplus
#import <google/protobuf/message.h>
#endif
@protocol PBObjcWrapper <NSObject>
-(instancetype) initWithProtocolData:(NSData*) data;
#ifdef __cplusplus
-(instancetype) initWithProtocolObj:(google::protobuf::Message *)pbobj;
#endif
-(NSData*) getProtocolData;
-(NSMutableDictionary*) asDict;
@end
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/beagleboard-xm-ubuntu:cosmic-build
ENV NODE_VERSION 12.20.1
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "7283ced5d7c0cc036a35bc2e64b23e7d4b348848170567880edabcf5279f4f8a node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.20.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
package storage
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
)
func TestSetBinlogPosition(t *testing.T) {
dir, err := ioutil.TempDir("", "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
file := filepath.Join(dir, "temp.db")
store := &BoltDBStore{}
store.Open(file)
store.SetBinlogPosition(&BinlogInformation{File: "binlog001.log", Position: 1234567890})
binlogInfo, err := store.GetBinlogPosition()
if err != nil || binlogInfo.File != "binlog001.log" || binlogInfo.Position != 1234567890 {
t.Error("failed")
}
}
|
Java
|
/*
* Copyright 2005-2017 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
/*****************************
* Enrico Fucile
****************************/
#include "grib_api_internal.h"
/*
This is used by make_class.pl
START_CLASS_DEF
CLASS = accessor
SUPER = grib_accessor_class_long
IMPLEMENTS = unpack_long
IMPLEMENTS = init
MEMBERS = const char* numberOfValues
MEMBERS = const char* bitsPerValue
MEMBERS = const char* offsetBeforeData
MEMBERS = const char* offsetAfterData
MEMBERS = const char* unusedBits
END_CLASS_DEF
*/
/* START_CLASS_IMP */
/*
Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "accessor.class" and rerun ./make_class.pl
*/
static int unpack_long(grib_accessor*, long* val,size_t *len);
static void init(grib_accessor*,const long, grib_arguments* );
static void init_class(grib_accessor_class*);
typedef struct grib_accessor_number_of_coded_values {
grib_accessor att;
/* Members defined in gen */
/* Members defined in long */
/* Members defined in number_of_coded_values */
const char* numberOfValues;
const char* bitsPerValue;
const char* offsetBeforeData;
const char* offsetAfterData;
const char* unusedBits;
} grib_accessor_number_of_coded_values;
extern grib_accessor_class* grib_accessor_class_long;
static grib_accessor_class _grib_accessor_class_number_of_coded_values = {
&grib_accessor_class_long, /* super */
"number_of_coded_values", /* name */
sizeof(grib_accessor_number_of_coded_values), /* size */
0, /* inited */
&init_class, /* init_class */
&init, /* init */
0, /* post_init */
0, /* free mem */
0, /* describes himself */
0, /* get length of section */
0, /* get length of string */
0, /* get number of values */
0, /* get number of bytes */
0, /* get offset to bytes */
0, /* get native type */
0, /* get sub_section */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
&unpack_long, /* grib_unpack procedures long */
0, /* grib_pack procedures double */
0, /* grib_unpack procedures double */
0, /* grib_pack procedures string */
0, /* grib_unpack procedures string */
0, /* grib_pack procedures bytes */
0, /* grib_unpack procedures bytes */
0, /* pack_expression */
0, /* notify_change */
0, /* update_size */
0, /* preferred_size */
0, /* resize */
0, /* nearest_smaller_value */
0, /* next accessor */
0, /* compare vs. another accessor */
0, /* unpack only ith value */
0, /* unpack a subarray */
0, /* clear */
};
grib_accessor_class* grib_accessor_class_number_of_coded_values = &_grib_accessor_class_number_of_coded_values;
static void init_class(grib_accessor_class* c)
{
c->dump = (*(c->super))->dump;
c->next_offset = (*(c->super))->next_offset;
c->string_length = (*(c->super))->string_length;
c->value_count = (*(c->super))->value_count;
c->byte_count = (*(c->super))->byte_count;
c->byte_offset = (*(c->super))->byte_offset;
c->get_native_type = (*(c->super))->get_native_type;
c->sub_section = (*(c->super))->sub_section;
c->pack_missing = (*(c->super))->pack_missing;
c->is_missing = (*(c->super))->is_missing;
c->pack_long = (*(c->super))->pack_long;
c->pack_double = (*(c->super))->pack_double;
c->unpack_double = (*(c->super))->unpack_double;
c->pack_string = (*(c->super))->pack_string;
c->unpack_string = (*(c->super))->unpack_string;
c->pack_bytes = (*(c->super))->pack_bytes;
c->unpack_bytes = (*(c->super))->unpack_bytes;
c->pack_expression = (*(c->super))->pack_expression;
c->notify_change = (*(c->super))->notify_change;
c->update_size = (*(c->super))->update_size;
c->preferred_size = (*(c->super))->preferred_size;
c->resize = (*(c->super))->resize;
c->nearest_smaller_value = (*(c->super))->nearest_smaller_value;
c->next = (*(c->super))->next;
c->compare = (*(c->super))->compare;
c->unpack_double_element = (*(c->super))->unpack_double_element;
c->unpack_double_subarray = (*(c->super))->unpack_double_subarray;
c->clear = (*(c->super))->clear;
}
/* END_CLASS_IMP */
static void init(grib_accessor* a,const long l, grib_arguments* c)
{
int n=0;
grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a;
self->bitsPerValue = grib_arguments_get_name(a->parent->h,c,n++);
self->offsetBeforeData = grib_arguments_get_name(a->parent->h,c,n++);
self->offsetAfterData = grib_arguments_get_name(a->parent->h,c,n++);
self->unusedBits = grib_arguments_get_name(a->parent->h,c,n++);
self->numberOfValues = grib_arguments_get_name(a->parent->h,c,n++);
a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY;
a->flags |= GRIB_ACCESSOR_FLAG_FUNCTION;
a->length=0;
}
static int unpack_long(grib_accessor* a, long* val, size_t *len)
{
int ret=GRIB_SUCCESS;
long bpv=0;
long offsetBeforeData=0,offsetAfterData=0,unusedBits=0,numberOfValues;
grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a;
if((ret = grib_get_long_internal(a->parent->h, self->bitsPerValue,&bpv)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->offsetBeforeData,&offsetBeforeData)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->offsetAfterData,&offsetAfterData)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->unusedBits,&unusedBits)) != GRIB_SUCCESS)
return ret;
if ( bpv != 0 ) {
grib_context_log(a->parent->h->context,GRIB_LOG_DEBUG,"grib_accessor_number_of_coded_values: offsetAfterData=%ld offsetBeforeData=%ld unusedBits=%ld bpv=%ld\n",
offsetAfterData,offsetBeforeData,unusedBits,bpv);
*val=((offsetAfterData-offsetBeforeData)*8-unusedBits)/bpv;
} else {
if((ret = grib_get_long_internal(a->parent->h, self->numberOfValues,&numberOfValues)) != GRIB_SUCCESS)
return ret;
*val=numberOfValues;
}
return ret;
}
|
Java
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBigPicture.h"
#include "SkData.h"
#include "SkDrawable.h"
#include "SkLayerInfo.h"
#include "SkPictureRecorder.h"
#include "SkPictureUtils.h"
#include "SkRecord.h"
#include "SkRecordDraw.h"
#include "SkRecordOpts.h"
#include "SkRecorder.h"
#include "SkTypes.h"
SkPictureRecorder::SkPictureRecorder() {
fActivelyRecording = false;
fRecorder.reset(new SkRecorder(nullptr, SkRect::MakeWH(0, 0), &fMiniRecorder));
}
SkPictureRecorder::~SkPictureRecorder() {}
SkCanvas* SkPictureRecorder::beginRecording(const SkRect& cullRect,
SkBBHFactory* bbhFactory /* = nullptr */,
uint32_t recordFlags /* = 0 */) {
fCullRect = cullRect;
fFlags = recordFlags;
if (bbhFactory) {
fBBH.reset((*bbhFactory)(cullRect));
SkASSERT(fBBH.get());
}
if (!fRecord) {
fRecord.reset(new SkRecord);
}
SkRecorder::DrawPictureMode dpm = (recordFlags & kPlaybackDrawPicture_RecordFlag)
? SkRecorder::Playback_DrawPictureMode
: SkRecorder::Record_DrawPictureMode;
fRecorder->reset(fRecord.get(), cullRect, dpm, &fMiniRecorder);
fActivelyRecording = true;
return this->getRecordingCanvas();
}
SkCanvas* SkPictureRecorder::getRecordingCanvas() {
return fActivelyRecording ? fRecorder.get() : nullptr;
}
sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPicture() {
fActivelyRecording = false;
fRecorder->restoreToCount(1); // If we were missing any restores, add them now.
if (fRecord->count() == 0) {
return fMiniRecorder.detachAsPicture(fCullRect);
}
// TODO: delay as much of this work until just before first playback?
SkRecordOptimize(fRecord);
SkAutoTUnref<SkLayerInfo> saveLayerData;
if (fBBH && (fFlags & kComputeSaveLayerInfo_RecordFlag)) {
saveLayerData.reset(new SkLayerInfo);
}
SkDrawableList* drawableList = fRecorder->getDrawableList();
SkBigPicture::SnapshotArray* pictList =
drawableList ? drawableList->newDrawableSnapshot() : nullptr;
if (fBBH.get()) {
SkAutoTMalloc<SkRect> bounds(fRecord->count());
if (saveLayerData) {
SkRecordComputeLayers(fCullRect, *fRecord, bounds, pictList, saveLayerData);
} else {
SkRecordFillBounds(fCullRect, *fRecord, bounds);
}
fBBH->insert(bounds, fRecord->count());
// Now that we've calculated content bounds, we can update fCullRect, often trimming it.
// TODO: get updated fCullRect from bounds instead of forcing the BBH to return it?
SkRect bbhBound = fBBH->getRootBound();
SkASSERT((bbhBound.isEmpty() || fCullRect.contains(bbhBound))
|| (bbhBound.isEmpty() && fCullRect.isEmpty()));
fCullRect = bbhBound;
}
size_t subPictureBytes = fRecorder->approxBytesUsedBySubPictures();
for (int i = 0; pictList && i < pictList->count(); i++) {
subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]);
}
return sk_make_sp<SkBigPicture>(fCullRect, fRecord.release(), pictList, fBBH.release(),
saveLayerData.release(), subPictureBytes);
}
sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPictureWithCull(const SkRect& cullRect) {
fCullRect = cullRect;
return this->finishRecordingAsPicture();
}
void SkPictureRecorder::partialReplay(SkCanvas* canvas) const {
if (nullptr == canvas) {
return;
}
int drawableCount = 0;
SkDrawable* const* drawables = nullptr;
SkDrawableList* drawableList = fRecorder->getDrawableList();
if (drawableList) {
drawableCount = drawableList->count();
drawables = drawableList->begin();
}
SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, nullptr/*bbh*/, nullptr/*callback*/);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class SkRecordedDrawable : public SkDrawable {
SkAutoTUnref<SkRecord> fRecord;
SkAutoTUnref<SkBBoxHierarchy> fBBH;
SkAutoTDelete<SkDrawableList> fDrawableList;
const SkRect fBounds;
const bool fDoSaveLayerInfo;
public:
SkRecordedDrawable(SkRecord* record, SkBBoxHierarchy* bbh, SkDrawableList* drawableList,
const SkRect& bounds, bool doSaveLayerInfo)
: fRecord(SkRef(record))
, fBBH(SkSafeRef(bbh))
, fDrawableList(drawableList) // we take ownership
, fBounds(bounds)
, fDoSaveLayerInfo(doSaveLayerInfo)
{}
protected:
SkRect onGetBounds() override { return fBounds; }
void onDraw(SkCanvas* canvas) override {
SkDrawable* const* drawables = nullptr;
int drawableCount = 0;
if (fDrawableList) {
drawables = fDrawableList->begin();
drawableCount = fDrawableList->count();
}
SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, fBBH, nullptr/*callback*/);
}
SkPicture* onNewPictureSnapshot() override {
SkBigPicture::SnapshotArray* pictList = nullptr;
if (fDrawableList) {
// TODO: should we plumb-down the BBHFactory and recordFlags from our host
// PictureRecorder?
pictList = fDrawableList->newDrawableSnapshot();
}
SkAutoTUnref<SkLayerInfo> saveLayerData;
if (fBBH && fDoSaveLayerInfo) {
// TODO: can we avoid work by not allocating / filling these bounds?
SkAutoTMalloc<SkRect> scratchBounds(fRecord->count());
saveLayerData.reset(new SkLayerInfo);
SkRecordComputeLayers(fBounds, *fRecord, scratchBounds, pictList, saveLayerData);
}
size_t subPictureBytes = 0;
for (int i = 0; pictList && i < pictList->count(); i++) {
subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]);
}
// SkBigPicture will take ownership of a ref on both fRecord and fBBH.
// We're not willing to give up our ownership, so we must ref them for SkPicture.
return new SkBigPicture(fBounds, SkRef(fRecord.get()), pictList, SkSafeRef(fBBH.get()),
saveLayerData.release(), subPictureBytes);
}
};
sk_sp<SkDrawable> SkPictureRecorder::finishRecordingAsDrawable() {
fActivelyRecording = false;
fRecorder->flushMiniRecorder();
fRecorder->restoreToCount(1); // If we were missing any restores, add them now.
// TODO: delay as much of this work until just before first playback?
SkRecordOptimize(fRecord);
if (fBBH.get()) {
SkAutoTMalloc<SkRect> bounds(fRecord->count());
SkRecordFillBounds(fCullRect, *fRecord, bounds);
fBBH->insert(bounds, fRecord->count());
}
sk_sp<SkDrawable> drawable =
sk_make_sp<SkRecordedDrawable>(fRecord, fBBH, fRecorder->detachDrawableList(), fCullRect,
SkToBool(fFlags & kComputeSaveLayerInfo_RecordFlag));
// release our refs now, so only the drawable will be the owner.
fRecord.reset(nullptr);
fBBH.reset(nullptr);
return drawable;
}
|
Java
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace gov.va.medora.mdo.dao
{
public interface IEncounterDao
{
Appointment[] getAppointments();
Appointment[] getAppointments(string pid);
Appointment[] getFutureAppointments();
Appointment[] getFutureAppointments(string pid);
Appointment[] getAppointments(int pastDays, int futureDays);
Appointment[] getAppointments(string pid, int pastDays, int futureDays);
Appointment[] getMentalHealthAppointments();
string getAppointmentText(string apptId);
string getAppointmentText(string pid, string apptId);
Adt[] getInpatientMoves(string fromDate, string toDate);
Adt[] getInpatientMovesByCheckinId(string checkinId);
Adt[] getInpatientMoves();
Adt[] getInpatientMoves(string pid);
Adt[] getInpatientMoves(string fromDate, string toDate, string iterLength);
// Depreciate to lookupHospitalLocations
HospitalLocation[] lookupLocations(string target, string direction);
StringDictionary lookupHospitalLocations(string target);
string getLocationId(string locationName);
HospitalLocation[] getWards();
HospitalLocation[] getClinics(string target, string direction);
InpatientStay[] getStaysForWard(string wardId);
Drg[] getDRGRecords();
Visit[] getOutpatientVisits();
Visit[] getOutpatientVisits(string pid);
Visit[] getVisits(string fromDate, string toDate);
Visit[] getVisits(string pid, string fromDate, string toDate);
Visit[] getVisitsForDay(string theDate);
Visit[] getMentalHealthVisits();
InpatientStay[] getAdmissions();
InpatientStay[] getAdmissions(string pid);
string getServiceConnectedCategory(string initialCategory, string locationIen, bool outpatient);
string getOutpatientEncounterReport(string fromDate, string toDate, int nrpts);
string getOutpatientEncounterReport(string pid, string fromDate, string toDate, int nrpts);
string getAdmissionsReport(string fromDate, string toDate, int nrpts);
string getAdmissionsReport(string pid, string fromDate, string toDate, int nrpts);
string getExpandedAdtReport(string fromDate, string toDate, int nrpts);
string getExpandedAdtReport(string pid, string fromDate, string toDate, int nrpts);
string getDischargesReport(string fromDate, string toDate, int nrpts);
string getDischargesReport(string pid, string fromDate, string toDate, int nrpts);
string getTransfersReport(string fromDate, string toDate, int nrpts);
string getTransfersReport(string pid, string fromDate, string toDate, int nrpts);
string getFutureClinicVisitsReport(string fromDate, string toDate, int nrpts);
string getFutureClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts);
string getPastClinicVisitsReport(string fromDate, string toDate, int nrpts);
string getPastClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts);
string getTreatingSpecialtyReport(string fromDate, string toDate, int nrpts);
string getTreatingSpecialtyReport(string pid, string fromDate, string toDate, int nrpts);
string getCareTeamReport();
string getCareTeamReport(string pid);
string getDischargeDiagnosisReport(string fromDate, string toDate, int nrpts);
string getDischargeDiagnosisReport(string pid, string fromDate, string toDate, int nrpts);
IcdReport[] getIcdProceduresReport(string fromDate, string toDate, int nrpts);
IcdReport[] getIcdProceduresReport(string pid, string fromDate, string toDate, int nrpts);
IcdReport[] getIcdSurgeryReport(string fromDate, string toDate, int nrpts);
IcdReport[] getIcdSurgeryReport(string pid, string fromDate, string toDate, int nrpts);
string getCompAndPenReport(string fromDate, string toDate, int nrpts);
string getCompAndPenReport(string pid, string fromDate, string toDate, int nrpts);
DictionaryHashList getSpecialties();
DictionaryHashList getTeams();
Adt[] getInpatientDischarges(string pid);
InpatientStay[] getStayMovementsByDateRange(string fromDate, string toDate);
InpatientStay getStayMovements(string checkinId);
Site[] getSiteDivisions(string siteId);
PatientCareTeam getPatientCareTeamMembers(string station);
}
}
|
Java
|
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
@JNINamespace("webrtc::jni")
class VP8Decoder extends WrappedNativeVideoDecoder {
@Override
long createNativeDecoder() {
return nativeCreateDecoder();
}
static native long nativeCreateDecoder();
}
|
Java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.keyboard.internal;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Message;
import android.util.SparseArray;
import android.view.View;
import com.android.inputmethod.keyboard.PointerTracker;
import com.android.inputmethod.keyboard.internal.GestureTrail.Params;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
/**
* Draw gesture trail preview graphics during gesture.
*/
public final class GestureTrailsPreview extends AbstractDrawingPreview {
private final SparseArray<GestureTrail> mGestureTrails = CollectionUtils.newSparseArray();
private final Params mGestureTrailParams;
private final Paint mGesturePaint;
private int mOffscreenWidth;
private int mOffscreenHeight;
private int mOffscreenOffsetY;
private Bitmap mOffscreenBuffer;
private final Canvas mOffscreenCanvas = new Canvas();
private final Rect mOffscreenSrcRect = new Rect();
private final Rect mDirtyRect = new Rect();
private final Rect mGestureTrailBoundsRect = new Rect(); // per trail
private final DrawingHandler mDrawingHandler;
private static final class DrawingHandler
extends StaticInnerHandlerWrapper<GestureTrailsPreview> {
private static final int MSG_UPDATE_GESTURE_TRAIL = 0;
private final Params mGestureTrailParams;
public DrawingHandler(final GestureTrailsPreview outerInstance,
final Params gestureTrailParams) {
super(outerInstance);
mGestureTrailParams = gestureTrailParams;
}
@Override
public void handleMessage(final Message msg) {
final GestureTrailsPreview preview = getOuterInstance();
if (preview == null) return;
switch (msg.what) {
case MSG_UPDATE_GESTURE_TRAIL:
preview.getDrawingView().invalidate();
break;
}
}
public void postUpdateGestureTrailPreview() {
removeMessages(MSG_UPDATE_GESTURE_TRAIL);
sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_TRAIL),
mGestureTrailParams.mUpdateInterval);
}
}
public GestureTrailsPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) {
super(drawingView);
mGestureTrailParams = new Params(mainKeyboardViewAttr);
mDrawingHandler = new DrawingHandler(this, mGestureTrailParams);
final Paint gesturePaint = new Paint();
gesturePaint.setAntiAlias(true);
gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
mGesturePaint = gesturePaint;
}
@Override
public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) {
mOffscreenOffsetY = (int)(
height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
mOffscreenWidth = width;
mOffscreenHeight = mOffscreenOffsetY + height;
}
@Override
public void onDetachFromWindow() {
freeOffscreenBuffer();
}
private void freeOffscreenBuffer() {
if (mOffscreenBuffer != null) {
mOffscreenBuffer.recycle();
mOffscreenBuffer = null;
}
}
private void mayAllocateOffscreenBuffer() {
if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth
&& mOffscreenBuffer.getHeight() == mOffscreenHeight) {
return;
}
freeOffscreenBuffer();
mOffscreenBuffer = Bitmap.createBitmap(
mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888);
mOffscreenCanvas.setBitmap(mOffscreenBuffer);
mOffscreenCanvas.translate(0, mOffscreenOffsetY);
}
private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint,
final Rect dirtyRect) {
// Clear previous dirty rectangle.
if (!dirtyRect.isEmpty()) {
paint.setColor(Color.TRANSPARENT);
paint.setStyle(Paint.Style.FILL);
offscreenCanvas.drawRect(dirtyRect, paint);
}
dirtyRect.setEmpty();
boolean needsUpdatingGestureTrail = false;
// Draw gesture trails to offscreen buffer.
synchronized (mGestureTrails) {
// Trails count == fingers count that have ever been active.
final int trailsCount = mGestureTrails.size();
for (int index = 0; index < trailsCount; index++) {
final GestureTrail trail = mGestureTrails.valueAt(index);
needsUpdatingGestureTrail |= trail.drawGestureTrail(offscreenCanvas, paint,
mGestureTrailBoundsRect, mGestureTrailParams);
// {@link #mGestureTrailBoundsRect} has bounding box of the trail.
dirtyRect.union(mGestureTrailBoundsRect);
}
}
return needsUpdatingGestureTrail;
}
/**
* Draws the preview
* @param canvas The canvas where the preview is drawn.
*/
@Override
public void drawPreview(final Canvas canvas) {
if (!isPreviewEnabled()) {
return;
}
mayAllocateOffscreenBuffer();
// Draw gesture trails to offscreen buffer.
final boolean needsUpdatingGestureTrail = drawGestureTrails(
mOffscreenCanvas, mGesturePaint, mDirtyRect);
if (needsUpdatingGestureTrail) {
mDrawingHandler.postUpdateGestureTrailPreview();
}
// Transfer offscreen buffer to screen.
if (!mDirtyRect.isEmpty()) {
mOffscreenSrcRect.set(mDirtyRect);
mOffscreenSrcRect.offset(0, mOffscreenOffsetY);
canvas.drawBitmap(mOffscreenBuffer, mOffscreenSrcRect, mDirtyRect, null);
// Note: Defer clearing the dirty rectangle here because we will get cleared
// rectangle on the canvas.
}
}
/**
* Set the position of the preview.
* @param tracker The new location of the preview is based on the points in PointerTracker.
*/
@Override
public void setPreviewPosition(final PointerTracker tracker) {
if (!isPreviewEnabled()) {
return;
}
GestureTrail trail;
synchronized (mGestureTrails) {
trail = mGestureTrails.get(tracker.mPointerId);
if (trail == null) {
trail = new GestureTrail();
mGestureTrails.put(tracker.mPointerId, trail);
}
}
trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime());
// TODO: Should narrow the invalidate region.
getDrawingView().invalidate();
}
}
|
Java
|
using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;
using AwsTools;
using IndexBackend;
namespace SlideshowCreator.AwsAccess
{
class DynamoDbInsert
{
public const int BATCH_SIZE = 25;
public static Dictionary<string, List<WriteRequest>> GetBatchInserts<T>(List<T> pocoModels) where T : IModel, new()
{
var batchWrite = new Dictionary<string, List<WriteRequest>> { [new T().GetTable()] = new List<WriteRequest>() };
foreach (var pocoModel in pocoModels)
{
var dyamoDbModel = Conversion<T>.ConvertToDynamoDb(pocoModel);
var putRequest = new PutRequest(dyamoDbModel);
var writeRequest = new WriteRequest(putRequest);
batchWrite[new T().GetTable()].Add(writeRequest);
}
return batchWrite;
}
}
}
|
Java
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admingui.devtests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
public class JavaMessageServiceTest extends BaseSeleniumTestClass {
public static final String DEFAULT_JMS_HOST = "default_JMS_host";
@Test
public void testJmsService() {
gotoDasPage();
final String timeout = Integer.toString(generateRandomNumber(90));
final String interval = Integer.toString(generateRandomNumber(10));
final String attempts = Integer.toString(generateRandomNumber(10));
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link");
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", timeout);
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", interval);
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", attempts);
Select select = new Select(driver.findElement(By.id("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:behaviorProp:Behavior")));
select.selectByVisibleText("priority");
int count = addTableRow("propertyForm:propertyContentPage:basicTable", "propertyForm:propertyContentPage:basicTable:topActionsGroup1:addSharedTableButton");
sleep(500);
setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col2:col1St", "property" + generateRandomString());
sleep(500);
setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col3:col1St", "value");
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
gotoDasPage();
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link");
assertEquals(timeout, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", "value"));
assertEquals(interval, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", "value"));
assertEquals(attempts, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", "value"));
assertTableRowCount("propertyForm:propertyContentPage:basicTable", count);
//delete the property used to test
clickByIdAction("propertyForm:propertyContentPage:basicTable:_tableActionsTop:_selectMultipleButton:_selectMultipleButton_image");
clickByIdAction("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1");
waitforBtnDisable("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1");
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
}
@Test
public void testJmsHosts() {
gotoDasPage();
String hostText = "host" + generateRandomString();
String host = "somemachine" + generateRandomNumber(1000);
String port = Integer.toString(generateRandomNumber(32768));
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link");
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", host);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:PortProp:Port", port);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:AdminUserProp:AdminUser", "admin");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:newPasswordProp:NewPassword", "admin");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:confirmPasswordProp:ConfirmPassword", "admin");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:configs", hostText, "colName");
assertEquals(hostText, getText(prefix + "colName:link"));
String clickId = prefix + "colName:link";
clickByIdAction(clickId);
assertEquals(host, getValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "value"));
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
//delete related jms host
String deleteRow = prefix + "col0:select";
clickByIdAction(deleteRow);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
}
@Test
public void testJmsHostInNonServerConfig() {
String hostText = "host" + generateRandomString();
String instanceName = "in" + generateRandomString();
final String LINK_HOSTS = "treeForm:tree:configurations:" + instanceName + "-config:jmsConfiguration:jmsHosts:jmsHosts_link";
StandaloneTest sat = new StandaloneTest();
sat.createStandAloneInstance(instanceName);
sat.startInstance(instanceName);
// Create new JMS Host for the standalone instance's config
clickAndWait(LINK_HOSTS);
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "localhost");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
// Delete the default host for the SA instance
gotoDasPage();
clickAndWait(LINK_HOSTS);
String prefix = getTableRowByValue("propertyForm:configs", DEFAULT_JMS_HOST, "colName");
String deleteRow = prefix + "col0:select";
clickByIdAction(deleteRow);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
// Verify that the DAS still has the default JMS Host
gotoDasPage();
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link");
assertEquals(DEFAULT_JMS_HOST, getText(prefix + "colName:link"));
// Delete SA config's new host
gotoDasPage();
clickAndWait(LINK_HOSTS);
String prefix1 = getTableRowByValue("propertyForm:configs", hostText, "colName");
String deleteRow1 = prefix1 + "col0:select";
clickByIdAction(deleteRow1);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
sat.deleteAllStandaloneInstances();
}
// //This tests need to be rewrite and retested after the issue has been resolved
// @Test
// public void testJmsPhysicalDestinations() {
// gotoDasPage();
// final String name = "dest" + generateRandomString();
// final String maxUnconsumed = Integer.toString(generateRandomNumber(100));
// final String maxMessageSize = Integer.toString(generateRandomNumber(100));
// final String maxTotalMemory = Integer.toString(generateRandomNumber(100));
// final String maxProducers = Integer.toString(generateRandomNumber(500));
// final String consumerFlowLimit = Integer.toString(generateRandomNumber(5000));
//
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:serverInstTabs:jmsPhysDest");
// clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
//
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:NameTextProp:NameText", name);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", maxUnconsumed);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", maxMessageSize);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", maxTotalMemory);
// Select select = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:typeProp:type")));
// select.selectByVisibleText("javax.jms.Queue");
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumProducersProp:maxNumProducers", maxProducers);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", consumerFlowLimit);
// Select select1 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:useDmqProp:useDmq")));
// select1.selectByVisibleText("false");
// Select select2 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled")));
// select2.selectByVisibleText("true");
// clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:newButton");
//
// String prefix = getTableRowByValue("propertyForm:configs", name, "col1");
// assertEquals(name, getText(prefix + "col1:nameCol"));
//
// String clickId = prefix + "col1:nameCol";
// clickByIdAction(clickId);
//
// assertEquals(maxUnconsumed, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", "value"));
// assertEquals(maxMessageSize, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", "value"));
// assertEquals(maxTotalMemory, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", "value"));
//
// assertEquals(consumerFlowLimit, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", "value"));
// assertEquals("true", getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled", "value"));
// clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:cancelButton");
//
// String selectId = prefix + "col0:select";
// clickByIdAction(selectId);;
// clickAndWait("propertyForm:configs:topActionsGroup1:flushButton");
//
// gotoDasPage();
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:serverInstTabs:jmsPhysDest");
// deleteRow("propertyForm:configs:topActionsGroup1:deleteButton", "propertyForm:configs", name);
// }
@Test
public void testMasterBroker() {
ClusterTest ct = new ClusterTest();
try {
final String FIELD_MASTER_BROKER = "propertyForm:propertyContentPage:propertySheet:propertSectionTextField:maseterBrokerProp:MasterBroker";
String clusterName = "clusterName" + generateRandomString();
ct.deleteAllCluster();
final String instance1 = clusterName + generateRandomString();
final String instance2 = clusterName + generateRandomString();
ct.createCluster(clusterName, instance1, instance2);
final String ELEMENT_JMS_LINK = "treeForm:tree:configurations:" + clusterName + "-config:jmsConfiguration:jmsConfiguration_link";
clickAndWait(ELEMENT_JMS_LINK);
Select select = new Select(driver.findElement(By.id(FIELD_MASTER_BROKER)));
select.selectByVisibleText(instance2);
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
clickAndWait(ELEMENT_JMS_LINK);
assertEquals(instance2, getValue(FIELD_MASTER_BROKER, "value"));
} finally {
ct.deleteAllCluster();
}
}
}
|
Java
|
/** @file
Provide Boot Manager related library APIs.
Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.<BR>
(C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _UEFI_BOOT_MANAGER_LIB_H_
#define _UEFI_BOOT_MANAGER_LIB_H_
#include <Protocol/DriverHealth.h>
#include <Library/SortLib.h>
//
// Boot Manager load option library functions.
//
//
// Load Option Type
//
typedef enum {
LoadOptionTypeDriver,
LoadOptionTypeSysPrep,
LoadOptionTypeBoot,
LoadOptionTypePlatformRecovery,
LoadOptionTypeMax
} EFI_BOOT_MANAGER_LOAD_OPTION_TYPE;
typedef enum {
LoadOptionNumberMax = 0x10000,
LoadOptionNumberUnassigned = LoadOptionNumberMax
} EFI_BOOT_MANAGER_LOAD_OPTION_NUMBER;
//
// Common structure definition for DriverOption and BootOption
//
typedef struct {
//
// Data read from UEFI NV variables
//
UINTN OptionNumber; // #### numerical value, could be LoadOptionNumberUnassigned
EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; // LoadOptionTypeBoot or LoadOptionTypeDriver
UINT32 Attributes; // Load Option Attributes
CHAR16 *Description; // Load Option Description
EFI_DEVICE_PATH_PROTOCOL *FilePath; // Load Option Device Path
UINT8 *OptionalData; // Load Option optional data to pass into image
UINT32 OptionalDataSize; // Load Option size of OptionalData
EFI_GUID VendorGuid;
//
// Used at runtime
//
EFI_STATUS Status; // Status returned from boot attempt gBS->StartImage ()
CHAR16 *ExitData; // Exit data returned from gBS->StartImage ()
UINTN ExitDataSize; // Size of ExitData
} EFI_BOOT_MANAGER_LOAD_OPTION;
/**
Returns an array of load options based on the EFI variable
L"BootOrder"/L"DriverOrder" and the L"Boot####"/L"Driver####" variables impled by it.
#### is the hex value of the UINT16 in each BootOrder/DriverOrder entry.
@param LoadOptionCount Returns number of entries in the array.
@param LoadOptionType The type of the load option.
@retval NULL No load options exist.
@retval !NULL Array of load option entries.
**/
EFI_BOOT_MANAGER_LOAD_OPTION *
EFIAPI
EfiBootManagerGetLoadOptions (
OUT UINTN *LoadOptionCount,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType
);
/**
Free an array of load options returned from EfiBootManagerGetLoadOptions().
@param LoadOptions Pointer to the array of load options to free.
@param LoadOptionCount Number of array entries in LoadOptions.
@return EFI_SUCCESS LoadOptions was freed.
@return EFI_INVALID_PARAMETER LoadOptions is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeLoadOptions (
IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions,
IN UINTN LoadOptionCount
);
/**
Initialize a load option.
@param Option Pointer to the load option to be initialized.
@param OptionNumber Option number of the load option.
@param OptionType Type of the load option.
@param Attributes Attributes of the load option.
@param Description Description of the load option.
@param FilePath Device path of the load option.
@param OptionalData Optional data of the load option.
@param OptionalDataSize Size of the optional data of the load option.
@retval EFI_SUCCESS The load option was initialized successfully.
@retval EFI_INVALID_PARAMETER Option, Description or FilePath is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerInitializeLoadOption (
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option,
IN UINTN OptionNumber,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType,
IN UINT32 Attributes,
IN CHAR16 *Description,
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
IN UINT8 *OptionalData,
IN UINT32 OptionalDataSize
);
/**
Free a load option created by EfiBootManagerInitializeLoadOption()
or EfiBootManagerVariableToLoadOption().
@param LoadOption Pointer to the load option to free.
CONCERN: Check Boot#### instead of BootOrder, optimize, spec clarify
@return EFI_SUCCESS LoadOption was freed.
@return EFI_INVALID_PARAMETER LoadOption is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeLoadOption (
IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Initialize the load option from the VariableName.
@param VariableName EFI Variable name which could be Boot#### or
Driver####
@param LoadOption Pointer to the load option to be initialized
@retval EFI_SUCCESS The option was created
@retval EFI_INVALID_PARAMETER VariableName or LoadOption is NULL.
@retval EFI_NOT_FOUND The variable specified by VariableName cannot be found.
**/
EFI_STATUS
EFIAPI
EfiBootManagerVariableToLoadOption (
IN CHAR16 *VariableName,
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Create the Boot#### or Driver#### variable from the load option.
@param LoadOption Pointer to the load option.
@retval EFI_SUCCESS The variable was created.
@retval Others Error status returned by RT->SetVariable.
**/
EFI_STATUS
EFIAPI
EfiBootManagerLoadOptionToVariable (
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
This function will register the new Boot####, Driver#### or SysPrep#### option.
After the *#### is updated, the *Order will also be updated.
@param Option Pointer to load option to add. If on input
Option->OptionNumber is LoadOptionNumberUnassigned,
then on output Option->OptionNumber is updated to
the number of the new Boot####,
Driver#### or SysPrep#### option.
@param Position Position of the new load option to put in the ****Order variable.
@retval EFI_SUCCESS The *#### have been successfully registered.
@retval EFI_INVALID_PARAMETER The option number exceeds 0xFFFF.
@retval EFI_ALREADY_STARTED The option number of Option is being used already.
Note: this API only adds new load option, no replacement support.
@retval EFI_OUT_OF_RESOURCES There is no free option number that can be used when the
option number specified in the Option is LoadOptionNumberUnassigned.
@return Status codes of gRT->SetVariable ().
**/
EFI_STATUS
EFIAPI
EfiBootManagerAddLoadOptionVariable (
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option,
IN UINTN Position
);
/**
Delete the load option according to the OptionNumber and OptionType.
Only the BootOrder/DriverOrder is updated to remove the reference of the OptionNumber.
@param OptionNumber Option number of the load option.
@param OptionType Type of the load option.
@retval EFI_NOT_FOUND The load option cannot be found.
@retval EFI_SUCCESS The load option was deleted.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDeleteLoadOptionVariable (
IN UINTN OptionNumber,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType
);
/**
Sort the load options. The DriverOrder/BootOrder variables will be re-created to
reflect the new order.
@param OptionType The type of the load option.
@param CompareFunction The comparator function pointer.
**/
VOID
EFIAPI
EfiBootManagerSortLoadOptionVariable (
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType,
IN SORT_COMPARE CompareFunction
);
/**
Return the index of the load option in the load option array.
The function consider two load options are equal when the
OptionType, Attributes, Description, FilePath and OptionalData are equal.
@param Key Pointer to the load option to be found.
@param Array Pointer to the array of load options to be found.
@param Count Number of entries in the Array.
@retval -1 Key wasn't found in the Array.
@retval 0 ~ Count-1 The index of the Key in the Array.
**/
INTN
EFIAPI
EfiBootManagerFindLoadOption (
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key,
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array,
IN UINTN Count
);
//
// Boot Manager hot key library functions.
//
#pragma pack(1)
///
/// EFI Key Option.
///
typedef struct {
///
/// Specifies options about how the key will be processed.
///
EFI_BOOT_KEY_DATA KeyData;
///
/// The CRC-32 which should match the CRC-32 of the entire EFI_LOAD_OPTION to
/// which BootOption refers. If the CRC-32s do not match this value, then this key
/// option is ignored.
///
UINT32 BootOptionCrc;
///
/// The Boot#### option which will be invoked if this key is pressed and the boot option
/// is active (LOAD_OPTION_ACTIVE is set).
///
UINT16 BootOption;
///
/// The key codes to compare against those returned by the
/// EFI_SIMPLE_TEXT_INPUT and EFI_SIMPLE_TEXT_INPUT_EX protocols.
/// The number of key codes (0-3) is specified by the EFI_KEY_CODE_COUNT field in KeyOptions.
///
EFI_INPUT_KEY Keys[3];
UINT16 OptionNumber;
} EFI_BOOT_MANAGER_KEY_OPTION;
#pragma pack()
/**
Start the hot key service so that the key press can trigger the boot option.
@param HotkeyTriggered Return the waitable event and it will be signaled
when a valid hot key is pressed.
@retval EFI_SUCCESS The hot key service is started.
**/
EFI_STATUS
EFIAPI
EfiBootManagerStartHotkeyService (
IN EFI_EVENT *HotkeyTriggered
);
//
// Modifier for EfiBootManagerAddKeyOptionVariable and EfiBootManagerDeleteKeyOptionVariable
//
#define EFI_BOOT_MANAGER_SHIFT_PRESSED 0x00000001
#define EFI_BOOT_MANAGER_CONTROL_PRESSED 0x00000002
#define EFI_BOOT_MANAGER_ALT_PRESSED 0x00000004
#define EFI_BOOT_MANAGER_LOGO_PRESSED 0x00000008
#define EFI_BOOT_MANAGER_MENU_KEY_PRESSED 0x00000010
#define EFI_BOOT_MANAGER_SYS_REQ_PRESSED 0x00000020
/**
Add the key option.
It adds the key option variable and the key option takes affect immediately.
@param AddedOption Return the added key option.
@param BootOptionNumber The boot option number for the key option.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS The key option is added.
@retval EFI_ALREADY_STARTED The hot key is already used by certain key option.
**/
EFI_STATUS
EFIAPI
EfiBootManagerAddKeyOptionVariable (
OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption, OPTIONAL
IN UINT16 BootOptionNumber,
IN UINT32 Modifier,
...
);
/**
Delete the Key Option variable and unregister the hot key
@param DeletedOption Return the deleted key options.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS The key option is deleted.
@retval EFI_NOT_FOUND The key option cannot be found.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDeleteKeyOptionVariable (
IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption, OPTIONAL
IN UINT32 Modifier,
...
);
/**
Register the key option to exit the waiting of the Boot Manager timeout.
Platform should ensure that the continue key option isn't conflict with
other boot key options.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS Successfully register the continue key option.
@retval EFI_ALREADY_STARTED The continue key option is already registered.
**/
EFI_STATUS
EFIAPI
EfiBootManagerRegisterContinueKeyOption (
IN UINT32 Modifier,
...
);
/**
Try to boot the boot option triggered by hot key.
**/
VOID
EFIAPI
EfiBootManagerHotkeyBoot (
VOID
);
//
// Boot Manager boot library functions.
//
/**
The function creates boot options for all possible bootable medias in the following order:
1. Removable BlockIo - The boot option only points to the removable media
device, like USB key, DVD, Floppy etc.
2. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
like HardDisk.
3. Non-BlockIo SimpleFileSystem - The boot option points to a device supporting
SimpleFileSystem Protocol, but not supporting BlockIo
protocol.
4. LoadFile - The boot option points to the media supporting
LoadFile protocol.
Reference: UEFI Spec chapter 3.3 Boot Option Variables Default Boot Behavior
The function won't delete the boot option not added by itself.
**/
VOID
EFIAPI
EfiBootManagerRefreshAllBootOption (
VOID
);
/**
Attempt to boot the EFI boot option. This routine sets L"BootCurent" and
signals the EFI ready to boot event. If the device path for the option starts
with a BBS device path a legacy boot is attempted. Short form device paths are
also supported via this rountine. A device path starting with
MEDIA_HARDDRIVE_DP, MSG_USB_WWID_DP, MSG_USB_CLASS_DP gets expaned out
to find the first device that matches. If the BootOption Device Path
fails the removable media boot algorithm is attempted (\EFI\BOOTIA32.EFI,
\EFI\BOOTX64.EFI,... only one file type is tried per processor type)
@param BootOption Boot Option to try and boot.
On return, BootOption->Status contains the boot status:
EFI_SUCCESS BootOption was booted
EFI_UNSUPPORTED BootOption isn't supported.
EFI_NOT_FOUND The BootOption was not found on the system
Others BootOption failed with this error status
**/
VOID
EFIAPI
EfiBootManagerBoot (
IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
Return the boot option corresponding to the Boot Manager Menu.
It may automatically create one if the boot option hasn't been created yet.
@param BootOption Return the Boot Manager Menu.
@retval EFI_SUCCESS The Boot Manager Menu is successfully returned.
@retval EFI_NOT_FOUND The Boot Manager Menu cannot be found.
@retval others Return status of gRT->SetVariable (). BootOption still points
to the Boot Manager Menu even the Status is not EFI_SUCCESS
and EFI_NOT_FOUND.
**/
EFI_STATUS
EFIAPI
EfiBootManagerGetBootManagerMenu (
EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
Get the next possible full path pointing to the load option.
The routine doesn't guarantee the returned full path points to an existing
file, and it also doesn't guarantee the existing file is a valid load option.
BmGetNextLoadOptionBuffer() guarantees.
@param FilePath The device path pointing to a load option.
It could be a short-form device path.
@param FullPath The full path returned by the routine in last call.
Set to NULL in first call.
@return The next possible full path pointing to the load option.
Caller is responsible to free the memory.
**/
EFI_DEVICE_PATH_PROTOCOL *
EFIAPI
EfiBootManagerGetNextLoadOptionDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
IN EFI_DEVICE_PATH_PROTOCOL *FullPath
);
/**
Get the load option by its device path.
@param FilePath The device path pointing to a load option.
It could be a short-form device path.
@param FullPath Return the full device path of the load option after
short-form device path expanding.
Caller is responsible to free it.
@param FileSize Return the load option size.
@return The load option buffer. Caller is responsible to free the memory.
**/
VOID *
EFIAPI
EfiBootManagerGetLoadOptionBuffer (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
OUT UINTN *FileSize
);
/**
The function enumerates all the legacy boot options, creates them and
registers them in the BootOrder variable.
**/
typedef
VOID
(EFIAPI *EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION) (
VOID
);
/**
The function boots a legacy boot option.
**/
typedef
VOID
(EFIAPI *EFI_BOOT_MANAGER_LEGACY_BOOT) (
IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
The function registers the legacy boot support capabilities.
@param RefreshLegacyBootOption The function pointer to create all the legacy boot options.
@param LegacyBoot The function pointer to boot the legacy boot option.
**/
VOID
EFIAPI
EfiBootManagerRegisterLegacyBootSupport (
EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption,
EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot
);
/**
Return the platform provided boot option description for the controller.
@param Handle Controller handle.
@param DefaultDescription Default boot description provided by core.
@return The callee allocated description string
or NULL if the handler wants to use DefaultDescription.
**/
typedef
CHAR16 *
(EFIAPI *EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER) (
IN EFI_HANDLE Handle,
IN CONST CHAR16 *DefaultDescription
);
/**
Register the platform provided boot description handler.
@param Handler The platform provided boot description handler
@retval EFI_SUCCESS The handler was registered successfully.
@retval EFI_ALREADY_STARTED The handler was already registered.
@retval EFI_OUT_OF_RESOURCES There is not enough resource to perform the registration.
**/
EFI_STATUS
EFIAPI
EfiBootManagerRegisterBootDescriptionHandler (
IN EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler
);
//
// Boot Manager connect and disconnect library functions
//
/**
This function will connect all the system driver to controller
first, and then special connect the default console, this make
sure all the system controller available and the platform default
console connected.
**/
VOID
EFIAPI
EfiBootManagerConnectAll (
VOID
);
/**
This function will create all handles associate with every device
path node. If the handle associate with one device path node can not
be created successfully, then still give chance to do the dispatch,
which load the missing drivers if possible.
@param DevicePathToConnect The device path which will be connected, it can be
a multi-instance device path
@param MatchingHandle Return the controller handle closest to the DevicePathToConnect
@retval EFI_SUCCESS All handles associate with every device path node
have been created.
@retval EFI_OUT_OF_RESOURCES There is no resource to create new handles.
@retval EFI_NOT_FOUND Create the handle associate with one device path
node failed.
@retval EFI_SECURITY_VIOLATION The user has no permission to start UEFI device
drivers on the DevicePath.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePathToConnect,
OUT EFI_HANDLE *MatchingHandle OPTIONAL
);
/**
This function will disconnect all current system handles.
gBS->DisconnectController() is invoked for each handle exists in system handle buffer.
If handle is a bus type handle, all childrens also are disconnected recursively by
gBS->DisconnectController().
**/
VOID
EFIAPI
EfiBootManagerDisconnectAll (
VOID
);
//
// Boot Manager console library functions
//
typedef enum {
ConIn,
ConOut,
ErrOut,
ConInDev,
ConOutDev,
ErrOutDev,
ConsoleTypeMax
} CONSOLE_TYPE;
/**
This function will connect all the console devices base on the console
device variable ConIn, ConOut and ErrOut.
@retval EFI_DEVICE_ERROR All the consoles were not connected due to an error.
@retval EFI_SUCCESS Success connect any one instance of the console
device path base on the variable ConVarName.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectAllDefaultConsoles (
VOID
);
/**
This function updates the console variable based on ConVarName. It can
add or remove one specific console device path from the variable
@param ConsoleType ConIn, ConOut, ErrOut, ConInDev, ConOutDev or ErrOutDev.
@param CustomizedConDevicePath The console device path to be added to
the console variable. Cannot be multi-instance.
@param ExclusiveDevicePath The console device path to be removed
from the console variable. Cannot be multi-instance.
@retval EFI_UNSUPPORTED The added device path is the same as a removed one.
@retval EFI_SUCCESS Successfully added or removed the device path from the
console variable.
**/
EFI_STATUS
EFIAPI
EfiBootManagerUpdateConsoleVariable (
IN CONSOLE_TYPE ConsoleType,
IN EFI_DEVICE_PATH_PROTOCOL *CustomizedConDevicePath,
IN EFI_DEVICE_PATH_PROTOCOL *ExclusiveDevicePath
);
/**
Connect the console device base on the variable ConVarName, if
device path of the ConVarName is multi-instance device path, if
anyone of the instances is connected success, then this function
will return success.
@param ConsoleType ConIn, ConOut or ErrOut.
@retval EFI_NOT_FOUND There is not any console devices connected
success
@retval EFI_SUCCESS Success connect any one instance of the console
device path base on the variable ConVarName.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectConsoleVariable (
IN CONSOLE_TYPE ConsoleType
);
/**
Query all the children of VideoController and return the device paths of all the
children that support GraphicsOutput protocol.
@param VideoController PCI handle of video controller.
@return Device paths of all the children that support GraphicsOutput protocol.
**/
EFI_DEVICE_PATH_PROTOCOL *
EFIAPI
EfiBootManagerGetGopDevicePath (
IN EFI_HANDLE VideoController
);
/**
Connect the platform active active video controller.
@param VideoController PCI handle of video controller.
@retval EFI_NOT_FOUND There is no active video controller.
@retval EFI_SUCCESS The video controller is connected.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectVideoController (
EFI_HANDLE VideoController OPTIONAL
);
//
// Boot Manager driver health library functions.
//
typedef struct {
EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth;
///
/// Driver relative handles
///
EFI_HANDLE DriverHealthHandle;
EFI_HANDLE ControllerHandle;
EFI_HANDLE ChildHandle;
///
/// Driver health messages of the specify Driver
///
EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList;
///
/// HII relative handles
///
EFI_HII_HANDLE HiiHandle;
///
/// Driver Health status
///
EFI_DRIVER_HEALTH_STATUS HealthStatus;
} EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO;
/**
Return all the Driver Health information.
When the cumulative health status of all the controllers managed by the
driver who produces the EFI_DRIVER_HEALTH_PROTOCOL is healthy, only one
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO entry is created for such
EFI_DRIVER_HEALTH_PROTOCOL instance.
Otherwise, every controller creates one EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO
entry. Additionally every child controller creates one
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO entry if the driver is a bus driver.
@param Count Return the count of the Driver Health information.
@retval NULL No Driver Health information is returned.
@retval !NULL Pointer to the Driver Health information array.
**/
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *
EFIAPI
EfiBootManagerGetDriverHealthInfo (
UINTN *Count
);
/**
Free the Driver Health information array.
@param DriverHealthInfo Pointer to array of the Driver Health information.
@param Count Count of the array.
@retval EFI_SUCCESS The array is freed.
@retval EFI_INVALID_PARAMETER The array is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeDriverHealthInfo (
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo,
UINTN Count
);
/**
Process (load and execute) the load option.
@param LoadOption Pointer to the load option.
@retval EFI_INVALID_PARAMETER The load option type is invalid,
or the load option file path doesn't point to a valid file.
@retval EFI_UNSUPPORTED The load option type is of LoadOptionTypeBoot.
@retval EFI_SUCCESS The load option is inactive, or successfully loaded and executed.
**/
EFI_STATUS
EFIAPI
EfiBootManagerProcessLoadOption (
EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Check whether the VariableName is a valid load option variable name
and return the load option type and option number.
@param VariableName The name of the load option variable.
@param OptionType Return the load option type.
@param OptionNumber Return the load option number.
@retval TRUE The variable name is valid; The load option type and
load option number are returned.
@retval FALSE The variable name is NOT valid.
**/
BOOLEAN
EFIAPI
EfiBootManagerIsValidLoadOptionVariableName (
IN CHAR16 *VariableName,
OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL,
OUT UINT16 *OptionNumber OPTIONAL
);
/**
Dispatch the deferred images that are returned from all DeferredImageLoad instances.
@retval EFI_SUCCESS At least one deferred image is loaded successfully and started.
@retval EFI_NOT_FOUND There is no deferred image.
@retval EFI_ACCESS_DENIED There are deferred images but all of them are failed to load.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDispatchDeferredImages (
VOID
);
#endif
|
Java
|
---
layout: post
title: "java GC 学习(四)"
subtitle: "\"分代垃圾回收\""
date: 2017-2-21 08:00:00
author: "Jht"
header-img: "img/java-bg.jpg"
catalog: true
tags:
- java
- jvm
- GC
---
## stop-the-world
选择哪种GC算法,stop-the-world都是不可避免的。一旦Stop-the-world发生,
除了GC所需的线程外,其他线程都将停止工作GC调优通常就是为了改善stop-the-world的时间。
## 基于的分代理论的垃圾回收
垃圾回收器的创建基于以下两个前提:
- 大多数对象的很快就会变得不可达
- 只有极少数情况会出现旧对象持有新对象的引用
这两条被称为”弱分代假设“。为了证明此假设,在HotSpot VM中物理内存空间被划分为两部分:
新生代(young generate)和老年代(old generation)。
### 新生代
大部分的新创建对象分配在新生代。因为大部分对象很快就会变得不可达,所以它们被分配在新生代,
然后消失不再。当对象从新生代移除时,我们称之为”minor GC“
### 老年代
存活在新生代中但未变为不可达的对象会被复制到老年代。一般来说老年代的内存空间比新生代大,
所以在老年代GC发生的频率较新生代低一些。当对象从老年代被移除时,我们称之为”major GC“(或者full GC)。
#### 方法区
其中存储着类和接口的元信息以及interned的字符串信息。所以这一区域并不是为老年代中存活下来的对象所定义的持久区。
方法区中也会发生GC,这里的GC同样也被称为major GC
#### 如果老年代的对象需要持有新生代对象的引用怎么办?
在老年代中设计了”索引表(card table)“,是一个512字节的数据块。不管何时老年代需要持有新生代对象的引用时,
都会记录到此表中。当新生代中需要执行GC时,通过搜索此表决定新生代的对象是否为GC的目标对象,
从而降低遍历所有老年代对象进行检查的代价。该索引表使用写栅栏(write barrier)进行管理。
wite barrier是一个允许高性能执行minor GC的设备。尽管它会引入一个数据位的开销,
却能带来总体GC时间的大幅降低。
### 新生代的结构
新生代又可分为三个部分:
- 一个Eden区
- 两个Survivor区
对象在三个区域中的存活过程如下:
- 大多数新生对象都被分配在Eden区
- 第一次GC过后Eden中还存活的对象被移到其中一个Survivor区
- 再次GC过程中,Eden中还存活的对象会被移到之前已移入对象的Survivor区
- 一旦该Survivor区域无空间可用时,还存活的对象会从当前Survivor区移到另一个空的Survivor区。而当前Survivor区就会再次置为空状态
- 经过数次在两个Survivor区域移动后还存活的对象最后会被移动到老年代
下图是`Java VisualVm`的`Visual GC`监控图,Spaces包含新生代和老年代。

#### 注意
两个Survivor区域在任何时候必定有一个保持空白。如果同时有数据存在于两个Survivor区或者两个区域的的使用量都是0(空闲的时候有可能),
则意味着你的系统`可能`出现了运行错误。
### 更快的内存分配
在HotSpot VM中,使用了两项技术来实现更快的内存分配:
- 指针碰撞(bump-the-pointer)
- TLABs(Thread-Local Allocation Buffers)
Bump-the-pointer技术会跟踪在Eden上新创建的对象。由于新对象被分配在Eden空间的最上面,
所以后续如果有新对象创建,只需要判断新创建对象的大小是否满足剩余的Eden空间。
如果新对象满足要求,则其会被分配到Eden空间,同样位于Eden的最上面。所以当有新对象创建时,
只需要判断此新对象的大小即可,因此具有更快的内存分配速度。然而,在多线程环境下,
将会有别样的状况。为了满足多个线程在Eden空间上创建对象时的线程安全,不可避免的会引入锁,
因此随着锁竞争的开销,创建对象的性能也大打折扣。在HotSpot中正是通过TLABs解决了多线程问题。
TLABs允许每个线程在Eden上有自己的小片空间,线程只能访问其自己的TLAB区域,
因此bump-the-pointer能通过TLAB在不加锁的情况下完成快速的内存分配。
### 老年代垃圾回收
当老年代数据满时,便会执行老年代垃圾回收。根据GC算法的不同其执行过程也会有所区别,所以当你了解了每种GC的特点后再来理解老年代的垃圾回收就会容易很多。
7种GC类型:


#### Serial GC
参数控制:
- -XX:+UseSerialGC 串行收集器
Serial GC会损耗应用的性能,这种GC是为单核CPU上的桌面应用设计的。
Serial GC适用于CPU核数较少且使用的内存空间较小的场景。
只使用一个线程去回收。新生代、老年代使用串行回收;新生代复制算法、老年代标记-压缩
在老年代,则使用了一种称之为`mark-sweep-compact`的算法。
- 首先该算法需要在老年代中标记出存活着的对象
- 然后从前到后检查堆空间中存活的对象,并保持位置不变(把不再存活的对象清理出堆空间,称为`空间清理`)
- 最后,把存活的对象移到堆空间的前面部分以保持已使用的堆空间的连续性,从而把堆空间分为两部分:有对象的和无对象的(称为`空间压缩`)

#### ParNew GC
参数控制:
- -XX:+UseParNewGC ParNew收集器
- -XX:ParallelGCThreads 限制线程数量
ParNew收集器其实就是Serial收集器的多线程版本。新生代并行,老年代串行;新生代复制算法、老年代标记-压缩

#### Parallel GC
参数控制:
- -XX:+UseParallelGC 使用Parallel收集器
Parallel Scavenge收集器类似ParNew收集器,Parallel收集器更关注系统的吞吐量。
可以通过参数来打开自适应调节策略,虚拟机会根据当前系统的运行情况收集性能监控信息,
动态调整这些参数以提供最合适的停顿时间或最大的吞吐量;也可以通过参数控制GC的时间不大于多少毫秒或者比例;
新生代并行,老年代串行;新生代复制算法、老年代标记-压缩,Parallel GC又被称为`高吞吐GC(throughput GC)`
#### Parallel Old GC
- 参数控制: -XX:+UseParallelOldGC 使用Parallel收集器+ 老年代并行
Parallel Old是Parallel Scavenge收集器的老年代版本,使用多线程和标记-压缩算法。
#### CMS GC
- 参数控制:
- -XX:+UseConcMarkSweepGC 使用CMS收集器
- -XX:+ UseCMSCompactAtFullCollection Full GC后,进行一次碎片整理;整理过程是独占的,会引起停顿时间变长
- -XX:+CMSFullGCsBeforeCompaction 设置进行几次Full GC后,进行一次碎片整理
- -XX:ParallelCMSThreads 设定CMS的线程数量(一般情况约等于可用CPU数量)
CMS(Concurrent Mark Sweep)收集器是一种以获取最短回收停顿时间为目标的收集器。
目前很大一部分的Java应用都集中在互联网站或B/S系统的服务端上,这类应用尤其重视服务的响应速度,
希望系统停顿时间最短,以给用户带来较好的体验。
从名字(包含“Mark Sweep”)上就可以看出CMS收集器是基于“标记-清除”算法实现的,
它的运作过程相对于前面几种收集器来说要更复杂一些,整个过程分为4个步骤,包括:
- 初始标记(CMS initial mark)
- 并发标记(CMS concurrent mark)
- 重新标记(CMS remark)
- 并发清除(CMS concurrent sweep)
其中初始标记、重新标记这两个步骤仍然需要“Stop The World”。初始标记仅仅只是标记一下GC Roots能直接关联到的对象,
速度很快,并发标记阶段就是进行GC Roots Tracing的过程,而重新标记阶段则是为了修正并发标记期间,
因用户程序继续运作而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段稍长一些,
但远比并发标记的时间短。
由于整个过程中耗时最长的并发标记和并发清除过程中,收集器线程都可以与用户线程一起工作,
所以总体上来说,CMS收集器的内存回收过程是与用户线程一起并发地执行。老年代收集器(新生代使用ParNew)

#### G1 GC
G1是目前技术发展的最前沿成果之一,HotSpot开发团队赋予它的使命是未来可以替换掉CMS收集器。
与CMS收集器相比G1收集器有以下特点:
- 1. 空间整合,G1收集器采用标记整理算法,不会产生内存空间碎片。分配大对象时不会因为无法找到连续空间而提前触发下一次GC。
- 2. 可预测停顿,这是G1的另一大优势,降低停顿时间是G1和CMS的共同关注点,但G1除了追求低停顿外,还能建立可预测的停顿时间模型,能让使用者明确指定在一个长度为N毫秒的时间片段内,消耗在垃圾收集上的时间不得超过N毫秒,这几乎已经是实时Java(RTSJ)的垃圾收集器的特征了。
上面提到的垃圾收集器,收集的范围都是整个新生代或者老年代,而G1不再是这样。使用G1收集器时,
Java堆的内存布局与其他收集器有很大差别,它将整个Java堆划分为多个大小相等的独立区域(Region),
虽然还保留有新生代和老年代的概念,但新生代和老年代不再是物理隔阂了,它们都是一部分(可以不连续)Region的集合。
##### 新生代收集步骤
- 1、G1的新生代收集跟ParNew类似,当新生代占用达到一定比例的时候,开始出发收集。

- 2、下图被圈起的绿色部分为新生代的区域(region),经过Young GC后存活的对象被复制到一个或者多个区域空闲中,这些被填充的区域将是新的新生代;当新生代对象的年龄(逃逸过一次Young GC年龄增加1)已经达到某个阈值(ParNew默认15),被复制到老年代的区域中。
回收过程是停顿的(STW,Stop-The-Word);回收完成之后根据Young GC的统计信息调整Eden和Survivor的大小,有助于合理利用内存,提高回收效率。回收的过程多个回收线程并发收集。

##### 老年代收集步骤
和CMS类似,G1收集器收集老年代对象会有短暂停顿。
- 1、标记阶段,首先初始标记(Initial-Mark),这个阶段是停顿的(Stop the World Event),并且会触发一次普通Mintor GC。对应GC log:GC pause (young) (inital-mark)
- 2、Root Region Scanning,程序运行过程中会回收survivor区(存活到老年代),这一过程必须在young GC之前完成。
- 3、Concurrent Marking,在整个堆中进行并发标记(和应用程序并发执行),此过程可能被young GC中断。在并发标记阶段,若发现区域对象中的所有对象都是垃圾,那个这个区域会被立即回收(图中打X)。同时,并发标记过程中,会计算每个区域的对象活性(区域中存活对象的比例)。

- 4、Remark, 再标记,会有短暂停顿(STW)。再标记阶段是用来收集 并发标记阶段 产生新的垃圾(并发阶段和应用程序一同运行);G1中采用了比CMS更快的初始快照算法:snapshot-at-the-beginning (SATB)。
- 5、Copy/Clean up,多线程清除失活对象,会有STW。G1将回收区域的存活对象拷贝到新区域,清除Remember Sets,并发清空回收区域并把它返回到空闲区域链表中。

- 6、复制/清除过程后。回收区域的活性对象已经被集中回收到深蓝色和深绿色区域。

### 常用GC组合
| 新生代GC | 老年代GC | 描述 |
| ------------- |:-------------:| -----:|
|Serial | Serial Old |Serial和Serial Old都是单线程进行GC,GC时暂停所有应用线程。|
| ParNew | CMS | 使用-XX:+UseParNewGC选项来开启。ParNew是Serial的并行版本,可以指定GC线程数,默认GC线程数为CPU的数量。可以使用-XX:ParallelGCThreads选项指定GC的线程数。
如果指定了选项-XX:+UseConcMarkSweepGC选项,则新生代默认使用ParNew GC策略。 |
|ParNew| Serial Old | 使用-XX:+UseParNewGC选项来开启。新生代使用ParNew GC策略,年老代默认使用Serial Old GC策略。 |
|Parallel Scavenge| Serial Old | Parallel Scavenge策略主要是关注一个可控的吞吐量:应用程序运行时间 / (应用程序运行时间 + GC时间),可见这会使得CPU的利用率尽可能的高,适用于后台持久运行的应用程序,而不适用于交互较多的应用程序。 |
|Parallel Scavenge| Parallel Old | Parallel Old是Serial Old的并行版本 |
|G1GC| G1GC | XX:+UnlockExperimentalVMOptions -XX:+UseG1GC #开启<br> -XX:MaxGCPauseMillis =50 #暂停时间目标<br> -XX:GCPauseIntervalMillis =200 #暂停间隔目标<br> -XX:+G1YoungGenSize=512m #年轻代大小<br> -XX:SurvivorRatio=6 #幸存区比例 |
### 参考资料
[理解Java垃圾回收](http://www.codeceo.com/article/java-gc-1.html)
[GC算法 垃圾收集器](http://www.cnblogs.com/ityouknow/p/5614961.html)
|
Java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3beta1.model;
/**
* Metadata for a ConversationDatasets.ImportConversationData operation.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2ImportConversationDataOperationMetadata extends com.google.api.client.json.GenericJson {
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String conversationDataset;
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String createTime;
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleRpcStatus> partialFailures;
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @return value or {@code null} for none
*/
public java.lang.String getConversationDataset() {
return conversationDataset;
}
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @param conversationDataset conversationDataset or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setConversationDataset(java.lang.String conversationDataset) {
this.conversationDataset = conversationDataset;
return this;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @return value or {@code null} for none
*/
public String getCreateTime() {
return createTime;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @param createTime createTime or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setCreateTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @return value or {@code null} for none
*/
public java.util.List<GoogleRpcStatus> getPartialFailures() {
return partialFailures;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @param partialFailures partialFailures or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setPartialFailures(java.util.List<GoogleRpcStatus> partialFailures) {
this.partialFailures = partialFailures;
return this;
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata clone() {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.clone();
}
}
|
Java
|
# Simblocline DC. GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
/* Source code for textbook:
Flexible Reliable Software, by Henrik B. Christensen
CRC Press 2010
***********************************
Project developped in java by Henrik B. Christensen
C++ port by Robert Benkoczi
***********************************
*/
#ifndef __ILLEGALCOINEXCEPTION_H
#define __ILLEGALCOINEXCEPTION_H
#include <exception>
#include <string>
/** Exception representing illegal coin entry.
*/
class IllegalCoinException : public std::exception {
public:
/**
* @param e is a description of the exception
*/
IllegalCoinException( std::string e ) {};
};
#endif
|
Java
|
# Security Templates for AWS CloudFormation
Find the documentation here: http://templates.cloudonaut.io/en/stable/security/
## Developer notes
### RegionMap
To update the region map execute the following lines in your terminal:
```
$ regions=$(aws ec2 describe-regions --query "Regions[].RegionName" --output text)
$ for region in $regions; do ami=$(aws --region $region ec2 describe-images --filters "Name=name,Values=amzn-ami-hvm-2017.03.1.20170623-x86_64-gp2" --query "Images[0].ImageId" --output "text"); printf "'$region':\n AMI: '$ami'\n"; done
```
## Premium Support
We offer Premium Support for our CloudFormation templates: setting up environments based on our templates, adopting templates to specific use cases, resolving issues in production environments. [Hire us!](https://widdix.net/)
## About
A [cloudonaut.io](https://cloudonaut.io/templates-for-aws-cloudformation/) project. Engineered by [widdix](https://widdix.net).
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Sat Mar 16 04:11:58 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.messaging (BOM: * : All 2.3.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-03-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.wildfly.swarm.messaging (BOM: * : All 2.3.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.wildfly.swarm.messaging" class="title">Uses of Package<br>org.wildfly.swarm.messaging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.messaging">org.wildfly.swarm.messaging</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.messaging">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a> used by <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServer.html#org.wildfly.swarm.messaging">EnhancedServer</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServerConsumer.html#org.wildfly.swarm.messaging">EnhancedServerConsumer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingFraction.html#org.wildfly.swarm.messaging">MessagingFraction</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingServer.html#org.wildfly.swarm.messaging">MessagingServer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.html#org.wildfly.swarm.messaging">RemoteConnection</a>
<div class="block">Details for a remote message-queue connection.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Consumer.html#org.wildfly.swarm.messaging">RemoteConnection.Consumer</a>
<div class="block">Configuration functional interface for container-supplied objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Supplier.html#org.wildfly.swarm.messaging">RemoteConnection.Supplier</a>
<div class="block">Supplier functional interface for user-supplied object.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
Java
|
<!DOCTYPE HTML>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta charset="utf-8">
<base href="../../../../../../">
<script src="resources/sap/ui/test/starter/runTest.js"
data-sap-ui-testsuite="test-resources/sap/ui/mdc/qunit/field/testsuite.field.qunit"
data-sap-ui-test="FieldValueHelpUITableWrapper"></script>
</head>
<body>
<div id="qunit"></div>
<div id="content"></div>
</body>
</html>
|
Java
|
package org.jboss.resteasy.test;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.util.PortProvider;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import javax.ws.rs.client.ClientBuilder;
/**
* Test utility class
*
* @author <a href="justin@justinedelson.com">Justin Edelson</a>
* @version $Revision$
*/
public class TestPortProvider
{
/**
* Creates a ResteasyWebTarget using base request path.
*/
public static ResteasyWebTarget createTarget(String path)
{
return (ResteasyWebTarget) ClientBuilder.newClient().target(generateURL(path));
}
/**
* Create a Resteasy client proxy with an empty base request path.
*
* @param clazz the client interface class
* @return the proxy object
*/
public static <T> T createProxy(Class<T> clazz)
{
return createProxy(clazz, generateBaseUrl());
}
/**
* Create a Resteasy client proxy.
*
* @param clazz the client interface class
* @return the proxy object
* @path the base request path
*/
public static <T> T createProxy(Class<T> clazz, String url)
{
ResteasyWebTarget target = (ResteasyWebTarget) ResteasyClientBuilder.newClient().target(url);
return target.proxy(clazz);
}
/**
* Create a URI for the provided path, using the configured port
*
* @param path the request path
* @return a full URI
*/
public static URI createURI(String path)
{
return URI.create(generateURL(path));
}
/**
* Create a URL for the provided path, using the configured port
*
* @param path the request path
* @return a full URL
*/
public static URL createURL(String path) throws MalformedURLException
{
return new URL(generateURL(path));
}
/**
* Generate a base URL incorporating the configured port.
*
* @return a full URL
*/
public static String generateBaseUrl()
{
return generateURL("");
}
/**
* Generate a URL incorporating the configured port.
*
* @param path the path
* @return a full URL
*/
public static String generateURL(String path)
{
return String.format("http://%s:%d%s", getHost(), getPort(), path);
}
/**
* Look up the configured port number, first checking an environment variable (RESTEASY_PORT),
* then a system property (org.jboss.resteasy.port), and finally the default port (8081).
*
* @return the port number specified in either the environment or system properties
*/
public static int getPort()
{
return PortProvider.getPort();
}
/**
* Look up the configured hostname, first checking an environment variable (RESTEASY_HOST),
* then a system property (org.jboss.resteasy.host), and finally the default hostname (localhost).
*
* @return the host specified in either the environment or system properties
*/
public static String getHost()
{
return PortProvider.getHost();
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_111) on Wed Jan 04 22:31:13 EST 2017 -->
<title>FritzJohnMultipliers</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="FritzJohnMultipliers";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":9,"i4":10,"i5":10,"i6":10,"i7":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/FritzJohnMultipliers.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/drip/optimization/constrained/NecessarySufficientConditions.html" title="class in org.drip.optimization.constrained"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/optimization/constrained/FritzJohnMultipliers.html" target="_top">Frames</a></li>
<li><a href="FritzJohnMultipliers.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.drip.optimization.constrained</div>
<h2 title="Class FritzJohnMultipliers" class="title">Class FritzJohnMultipliers</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.drip.optimization.constrained.FritzJohnMultipliers</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">FritzJohnMultipliers</span>
extends java.lang.Object</pre>
<div class="block">FritzJohnMultipliers holds the Array of the Fritz John/KKT Multipliers for the Array of the Equality and
the Inequality Constraints, one per each Constraint. The References are:
- Boyd, S., and L. van den Berghe (2009): Convex Optimization, Cambridge University Press, Cambridge UK.
- Eustaquio, R., E. Karas, and A. Ribeiro (2008): Constraint Qualification for Nonlinear Programming,
Technical Report, Federal University of Parana.
- Karush, A. (1939): Minima of Functions of Several Variables with Inequalities as Side Constraints,
M. Sc., University of Chicago, Chicago IL.
- Kuhn, H. W., and A. W. Tucker (1951): Nonlinear Programming, Proceedings of the Second Berkeley
Symposium, University of California, Berkeley CA 481-492.
- Ruszczynski, A. (2006): Nonlinear Optimization, Princeton University Press, Princeton NJ.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Lakshmi Krishnamurthy</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#FritzJohnMultipliers-double-double:A-double:A-">FritzJohnMultipliers</a></span>(double dblObjectiveCoefficient,
double[] adblEquality,
double[] adblInequality)</code>
<div class="block">FritzJohnMultipliers Constructor</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#dualFeasibilityCheck--">dualFeasibilityCheck</a></span>()</code>
<div class="block">Indicate of the Multipliers constitute Valid Dual Feasibility</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>double[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#equalityConstraintCoefficient--">equalityConstraintCoefficient</a></span>()</code>
<div class="block">Retrieve the Array of the Equality Constraint Coefficients</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>double[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#inequalityConstraintCoefficient--">inequalityConstraintCoefficient</a></span>()</code>
<div class="block">Retrieve the Array of the Inequality Constraint Coefficients</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html" title="class in org.drip.optimization.constrained">FritzJohnMultipliers</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#KarushKuhnTucker-double:A-double:A-">KarushKuhnTucker</a></span>(double[] adblEquality,
double[] adblInequality)</code>
<div class="block">Construct a Standard KarushKuhnTucker (KKT) Instance of the Fritz John Multipliers</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numEqualityCoefficients--">numEqualityCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Equality Multiplier Coefficients</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numInequalityCoefficients--">numInequalityCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Inequality Multiplier Coefficients</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numTotalCoefficients--">numTotalCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Total KKT Multiplier Coefficients</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#objectiveCoefficient--">objectiveCoefficient</a></span>()</code>
<div class="block">Retrieve the Fritz John Objective Function Multiplier</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="FritzJohnMultipliers-double-double:A-double:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>FritzJohnMultipliers</h4>
<pre>public FritzJohnMultipliers(double dblObjectiveCoefficient,
double[] adblEquality,
double[] adblInequality)
throws java.lang.Exception</pre>
<div class="block">FritzJohnMultipliers Constructor</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>dblObjectiveCoefficient</code> - The Objective Function Coefficient</dd>
<dd><code>adblEquality</code> - Array of the Equality Constraint Coefficients</dd>
<dd><code>adblInequality</code> - Array of the Inequality Constraint Coefficients</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code> - Thrown if the Inputs are Invalid</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="KarushKuhnTucker-double:A-double:A-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KarushKuhnTucker</h4>
<pre>public static final <a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html" title="class in org.drip.optimization.constrained">FritzJohnMultipliers</a> KarushKuhnTucker(double[] adblEquality,
double[] adblInequality)</pre>
<div class="block">Construct a Standard KarushKuhnTucker (KKT) Instance of the Fritz John Multipliers</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>adblEquality</code> - Array of the Equality Constraint Coefficients</dd>
<dd><code>adblInequality</code> - Array of the Inequality Constraint Coefficients</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The KKT Instance of Fritz John Multipliers</dd>
</dl>
</li>
</ul>
<a name="objectiveCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>objectiveCoefficient</h4>
<pre>public double objectiveCoefficient()</pre>
<div class="block">Retrieve the Fritz John Objective Function Multiplier</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Fritz John Objective Function Multiplier</dd>
</dl>
</li>
</ul>
<a name="equalityConstraintCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equalityConstraintCoefficient</h4>
<pre>public double[] equalityConstraintCoefficient()</pre>
<div class="block">Retrieve the Array of the Equality Constraint Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Array of the Equality Constraint Coefficients</dd>
</dl>
</li>
</ul>
<a name="inequalityConstraintCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inequalityConstraintCoefficient</h4>
<pre>public double[] inequalityConstraintCoefficient()</pre>
<div class="block">Retrieve the Array of the Inequality Constraint Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Array of the Inequality Constraint Coefficients</dd>
</dl>
</li>
</ul>
<a name="numEqualityCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numEqualityCoefficients</h4>
<pre>public int numEqualityCoefficients()</pre>
<div class="block">Retrieve the Number of Equality Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Equality Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="numInequalityCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numInequalityCoefficients</h4>
<pre>public int numInequalityCoefficients()</pre>
<div class="block">Retrieve the Number of Inequality Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Inequality Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="numTotalCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numTotalCoefficients</h4>
<pre>public int numTotalCoefficients()</pre>
<div class="block">Retrieve the Number of Total KKT Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Total KKT Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="dualFeasibilityCheck--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>dualFeasibilityCheck</h4>
<pre>public boolean dualFeasibilityCheck()</pre>
<div class="block">Indicate of the Multipliers constitute Valid Dual Feasibility</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>TRUE - The Multipliers constitute Valid Dual Feasibility</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/FritzJohnMultipliers.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/drip/optimization/constrained/NecessarySufficientConditions.html" title="class in org.drip.optimization.constrained"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/optimization/constrained/FritzJohnMultipliers.html" target="_top">Frames</a></li>
<li><a href="FritzJohnMultipliers.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
# Ornithogalum transversale Pall. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Syndication;
namespace DncShowcaseHub.DataModel
{
class FeedItemIterator
{
private SyndicationFeed feed;
private int index;
public FeedItemIterator()
{
this.feed = null;
this.index = 0;
}
public void AttachFeed(SyndicationFeed feed)
{
this.feed = feed;
this.index = 0;
}
public bool MoveNext()
{
if (feed != null && index < feed.Items.Count - 1)
{
index++;
return true;
}
return false;
}
public void MovePrevious()
{
if (feed != null && index > 0)
{
index--;
}
}
public bool HasElements()
{
return feed != null && feed.Items.Count > 0;
}
public string GetTitle()
{
// Nothing to return yet.
if (!HasElements())
{
return "(no title)";
}
if (feed.Items[index].Title != null)
{
return WebUtility.HtmlDecode(feed.Items[index].Title.Text);
}
return "(no title)";
}
public string GetContent()
{
// Nothing to return yet.
if (!HasElements())
{
return "(no value)";
}
if ((feed.Items[index].Content != null) && (feed.Items[index].Content.Text != null))
{
return feed.Items[index].Content.Text;
}
else if (feed.Items[index].Summary != null && !string.IsNullOrEmpty(feed.Items[index].Summary.Text))
{
return feed.Items[index].Summary.Text;
}
return "(no value)";
}
public string GetIndexDescription()
{
// Nothing to return yet.
if (!HasElements())
{
return "0 of 0";
}
return String.Format("{0} of {1}", index + 1, feed.Items.Count);
}
public Uri GetEditUri()
{
// Nothing to return yet.
if (!HasElements())
{
return null;
}
return feed.Items[index].EditUri;
}
public SyndicationItem GetSyndicationItem()
{
// Nothing to return yet.
if (!HasElements())
{
return null;
}
return feed.Items[index];
}
internal string GetAuthor()
{
if (feed.Items[index].Authors != null &&
feed.Items[index].Authors.Count > 0)
{
string authors = "";
foreach (var author in feed.Items[index].Authors)
{
authors += (author.NodeValue + ",");
}
return authors.TrimEnd(',');
}
return "";
}
internal string GetUrlPath()
{
if (feed.Items[index].Links != null &&
feed.Items[index].Links.Count > 0)
{
return feed.Items[index].Links[0].Uri.AbsoluteUri;
}
return "";
}
}
}
|
Java
|
<?php
namespace db2eav\Classes;
class Value extends ValueBase {
public function __construct(){
}
public function __destruct(){
}
}
|
Java
|
package com.xiaochen.progressroundbutton;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by tanfujun on 15/9/4.
*/
public class AnimDownloadProgressButton extends TextView {
private Context mContext;
//背景画笔
private Paint mBackgroundPaint;
//按钮文字画笔
private volatile Paint mTextPaint;
//第一个点画笔
private Paint mDot1Paint;
//第二个点画笔
private Paint mDot2Paint;
//背景颜色
private int[] mBackgroundColor;
private int[] mOriginBackgroundColor;
//下载中后半部分后面背景颜色
private int mBackgroundSecondColor;
//文字颜色
private int mTextColor;
//覆盖后颜色
private int mTextCoverColor;
//文字大小
private float mAboveTextSize = 50;
private float mProgress = -1;
private float mToProgress;
private int mMaxProgress;
private int mMinProgress;
private float mProgressPercent;
private float mButtonRadius;
//两个点向右移动距离
private float mDot1transX;
private float mDot2transX;
private RectF mBackgroundBounds;
private LinearGradient mFillBgGradient;
private LinearGradient mProgressBgGradient;
private LinearGradient mProgressTextGradient;
//点运动动画
private AnimatorSet mDotAnimationSet;
//下载平滑动画
private ValueAnimator mProgressAnimation;
//记录当前文字
private CharSequence mCurrentText;
//普通状态
public static final int NORMAL = 0;
//下载中
public static final int DOWNLOADING = 1;
//有点运动状态
public static final int INSTALLING = 2;
private ButtonController mDefaultController;
private ButtonController mCustomerController;
private int mState;
public AnimDownloadProgressButton(Context context) {
this(context, null);
}
public AnimDownloadProgressButton(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
mContext = context;
initController();
initAttrs(context, attrs);
init();
setupAnimations();
}else {
initController();
}
}
private void initController() {
mDefaultController = new DefaultButtonController();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
ButtonController buttonController = switchController();
if (buttonController.enablePress()) {
if (mOriginBackgroundColor == null) {
mOriginBackgroundColor = new int[2];
mOriginBackgroundColor[0] = mBackgroundColor[0];
mOriginBackgroundColor[1] = mBackgroundColor[1];
}
if (this.isPressed()) {
int pressColorleft = buttonController.getPressedColor(mBackgroundColor[0]);
int pressColorright = buttonController.getPressedColor(mBackgroundColor[1]);
if (buttonController.enableGradient()) {
initGradientColor(pressColorleft, pressColorright);
} else {
initGradientColor(pressColorleft, pressColorleft);
}
} else {
if (buttonController.enableGradient()) {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[1]);
} else {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[0]);
}
}
invalidate();
}
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimDownloadProgressButton);
int bgColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_color, Color.parseColor("#6699ff"));
//初始化背景颜色数组
initGradientColor(bgColor, bgColor);
mBackgroundSecondColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_second_color, Color.LTGRAY);
mButtonRadius = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_radius, getMeasuredHeight() / 2);
mAboveTextSize = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_text_size, 50);
mTextColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_color, bgColor);
mTextCoverColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_covercolor, Color.WHITE);
boolean enableGradient = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_gradient, false);
boolean enablePress = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_press, false);
((DefaultButtonController) mDefaultController).setEnableGradient(enableGradient).setEnablePress(enablePress);
if (enableGradient){
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
a.recycle();
}
private void init() {
mMaxProgress = 100;
mMinProgress = 0;
mProgress = 0;
//设置背景画笔
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.FILL);
//设置文字画笔
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(mAboveTextSize);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//解决文字有时候画不出问题
setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint);
}
//设置第一个点画笔
mDot1Paint = new Paint();
mDot1Paint.setAntiAlias(true);
mDot1Paint.setTextSize(mAboveTextSize);
//设置第二个点画笔
mDot2Paint = new Paint();
mDot2Paint.setAntiAlias(true);
mDot2Paint.setTextSize(mAboveTextSize);
//初始化状态设为NORMAL
mState = NORMAL;
invalidate();
}
//初始化渐变色
private int[] initGradientColor(int leftColor, int rightColor) {
mBackgroundColor = new int[2];
mBackgroundColor[0] = leftColor;
mBackgroundColor[1] = rightColor;
return mBackgroundColor;
}
private void setupAnimations() {
//两个点向右移动动画
ValueAnimator dotMoveAnimation = ValueAnimator.ofFloat(0, 20);
TimeInterpolator pathInterpolator = PathInterpolatorCompat.create(0.11f, 0f, 0.12f, 1f);
dotMoveAnimation.setInterpolator(pathInterpolator);
dotMoveAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float transX = (float) animation.getAnimatedValue();
mDot1transX = transX;
mDot2transX = transX;
invalidate();
}
});
dotMoveAnimation.setDuration(1243);
dotMoveAnimation.setRepeatMode(ValueAnimator.RESTART);
dotMoveAnimation.setRepeatCount(ValueAnimator.INFINITE);
//两个点渐显渐隐动画
final ValueAnimator dotAlphaAnim = ValueAnimator.ofInt(0, 1243).setDuration(1243);
dotAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int time = (int) dotAlphaAnim.getAnimatedValue();
int dot1Alpha = calculateDot1AlphaByTime(time);
int dot2Alpha = calculateDot2AlphaByTime(time);
mDot1Paint.setColor(mTextCoverColor);
mDot2Paint.setColor(mTextCoverColor);
mDot1Paint.setAlpha(dot1Alpha);
mDot2Paint.setAlpha(dot2Alpha);
}
});
dotAlphaAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
mDot1Paint.setAlpha(0);
mDot2Paint.setAlpha(0);
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
dotAlphaAnim.setRepeatMode(ValueAnimator.RESTART);
dotAlphaAnim.setRepeatCount(ValueAnimator.INFINITE);
//两个点的动画集合
mDotAnimationSet = new AnimatorSet();
mDotAnimationSet.playTogether(dotAlphaAnim, dotMoveAnimation);
//ProgressBar的动画
mProgressAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500);
mProgressAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float timepercent = (float) animation.getAnimatedValue();
mProgress = ((mToProgress - mProgress) * timepercent + mProgress);
invalidate();
}
});
}
//第一个点透明度计算函数
private int calculateDot2AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 83) {
double DAlpha = 255.0 / 83.0 * time;
alpha = (int) DAlpha;
} else if (83 < time && time <= 1000) {
alpha = 255;
} else if (1000 < time && time <= 1083) {
double DAlpha = -255.0 / 83.0 * (time - 1083);
alpha = (int) DAlpha;
} else if (1083 < time && time <= 1243) {
alpha = 0;
} else {
alpha = 255;
}
return alpha;
}
//第二个点透明度计算函数
private int calculateDot1AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 160) {
alpha = 0;
} else if (160 < time && time <= 243) {
double DAlpha = 255.0 / 83.0 * (time - 160);
alpha = (int) DAlpha;
} else if (243 < time && time <= 1160) {
alpha = 255;
} else if (1160 < time && time <= 1243) {
double DAlpha = -255.0 / 83.0 * (time - 1243);
alpha = (int) DAlpha;
} else {
alpha = 255;
}
return alpha;
}
private ValueAnimator createDotAlphaAnimation(int i, Paint mDot1Paint, int i1, int i2, int i3) {
return new ValueAnimator();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isInEditMode()) {
drawing(canvas);
}
}
private void drawing(Canvas canvas) {
drawBackground(canvas);
drawTextAbove(canvas);
}
private void drawBackground(Canvas canvas) {
mBackgroundBounds = new RectF();
if (mButtonRadius == 0) {
mButtonRadius = getMeasuredHeight() / 2;
}
mBackgroundBounds.left = 2;
mBackgroundBounds.top = 2;
mBackgroundBounds.right = getMeasuredWidth() - 2;
mBackgroundBounds.bottom = getMeasuredHeight() - 2;
ButtonController buttonController = switchController();
//color
switch (mState) {
case NORMAL:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
if (mBackgroundPaint.getShader() != null) {
mBackgroundPaint.setShader(null);
}
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case DOWNLOADING:
if (buttonController.enableGradient()) {
mProgressPercent = mProgress / (mMaxProgress + 0f);
int[] colorList = new int[]{mBackgroundColor[0], mBackgroundColor[1], mBackgroundSecondColor};
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
colorList,
new float[]{0, mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setShader(mProgressBgGradient);
} else {
mProgressPercent = mProgress / (mMaxProgress + 0f);
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
new int[]{mBackgroundColor[0], mBackgroundSecondColor},
new float[]{mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setColor(mBackgroundColor[0]);
mBackgroundPaint.setShader(mProgressBgGradient);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case INSTALLING:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
mBackgroundPaint.setShader(null);
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
}
}
private void drawTextAbove(Canvas canvas) {
final float y = canvas.getHeight() / 2 - (mTextPaint.descent() / 2 + mTextPaint.ascent() / 2);
if (mCurrentText == null) {
mCurrentText = "";
}
final float textWidth = mTextPaint.measureText(mCurrentText.toString());
//color
switch (mState) {
case NORMAL:
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case DOWNLOADING:
//进度条压过距离
float coverlength = getMeasuredWidth() * mProgressPercent;
//开始渐变指示器
float indicator1 = getMeasuredWidth() / 2 - textWidth / 2;
//结束渐变指示器
float indicator2 = getMeasuredWidth() / 2 + textWidth / 2;
//文字变色部分的距离
float coverTextLength = textWidth / 2 - getMeasuredWidth() / 2 + coverlength;
float textProgress = coverTextLength / textWidth;
if (coverlength <= indicator1) {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextColor);
} else if (indicator1 < coverlength && coverlength <= indicator2) {
mProgressTextGradient = new LinearGradient((getMeasuredWidth() - textWidth) / 2, 0, (getMeasuredWidth() + textWidth) / 2, 0,
new int[]{mTextCoverColor, mTextColor},
new float[]{textProgress, textProgress + 0.001f},
Shader.TileMode.CLAMP);
mTextPaint.setColor(mTextColor);
mTextPaint.setShader(mProgressTextGradient);
} else {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
}
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case INSTALLING:
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 4 + mDot1transX, y, 4, mDot1Paint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 24 + mDot2transX, y, 4, mDot2Paint);
break;
}
}
private ButtonController switchController() {
if (mCustomerController != null) {
return mCustomerController;
} else {
return mDefaultController;
}
}
public int getState() {
return mState;
}
public void setState(int state) {
if (mState != state) {//状态确实有改变
this.mState = state;
invalidate();
if (state == AnimDownloadProgressButton.INSTALLING) {
//开启两个点动画
mDotAnimationSet.start();
} else if (state == NORMAL) {
mDotAnimationSet.cancel();
} else if (state == DOWNLOADING) {
mDotAnimationSet.cancel();
}
}
}
/**
* 设置按钮文字
*/
public void setCurrentText(CharSequence charSequence) {
mCurrentText = charSequence;
invalidate();
}
/**
* 设置带下载进度的文字
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setProgressText(String text, float progress) {
if (progress >= mMinProgress && progress < mMaxProgress) {
mCurrentText = text + getResources().getString(R.string.downloaded, (int) progress);
mToProgress = progress;
if (mProgressAnimation.isRunning()) {
mProgressAnimation.start();
} else {
mProgressAnimation.start();
}
} else if (progress < mMinProgress) {
mProgress = 0;
} else if (progress >= mMaxProgress) {
mProgress = 100;
mCurrentText = text + getResources().getString(R.string.downloaded, (int) mProgress);
invalidate();
}
}
public float getProgress() {
return mProgress;
}
public void setProgress(float progress) {
this.mProgress = progress;
}
/**
* Sometimes you should use the method to avoid memory leak
*/
public void removeAllAnim() {
mDotAnimationSet.cancel();
mDotAnimationSet.removeAllListeners();
mProgressAnimation.cancel();
mProgressAnimation.removeAllListeners();
}
public void setProgressBtnBackgroundColor(int color){
initGradientColor(color, color);
}
public void setProgressBtnBackgroundSecondColor(int color){
mBackgroundSecondColor = color;
}
public float getButtonRadius() {
return mButtonRadius;
}
public void setButtonRadius(float buttonRadius) {
mButtonRadius = buttonRadius;
}
public int getTextColor() {
return mTextColor;
}
@Override
public void setTextColor(int textColor) {
mTextColor = textColor;
}
public int getTextCoverColor() {
return mTextCoverColor;
}
public void setTextCoverColor(int textCoverColor) {
mTextCoverColor = textCoverColor;
}
public int getMinProgress() {
return mMinProgress;
}
public void setMinProgress(int minProgress) {
mMinProgress = minProgress;
}
public int getMaxProgress() {
return mMaxProgress;
}
public void setMaxProgress(int maxProgress) {
mMaxProgress = maxProgress;
}
public void enabelDefaultPress(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnablePress(enable);
}
}
public void enabelDefaultGradient(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnableGradient(enable);
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
}
@Override
public void setTextSize(float size) {
mAboveTextSize = size;
mTextPaint.setTextSize(size);
}
@Override
public float getTextSize() {
return mAboveTextSize;
}
public AnimDownloadProgressButton setCustomerController(ButtonController customerController) {
mCustomerController = customerController;
return this;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mState = ss.state;
mProgress = ss.progress;
mCurrentText = ss.currentText;
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState, (int) mProgress, mState, mCurrentText.toString());
}
public static class SavedState extends BaseSavedState {
private int progress;
private int state;
private String currentText;
public SavedState(Parcelable parcel, int progress, int state, String currentText) {
super(parcel);
this.progress = progress;
this.state = state;
this.currentText = currentText;
}
private SavedState(Parcel in) {
super(in);
progress = in.readInt();
state = in.readInt();
currentText = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(progress);
out.writeInt(state);
out.writeString(currentText);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
|
Java
|
Getting started with the i3 window manager on Linux
======

In my article [5 reasons the i3 window manager makes Linux better][1], I shared the top five reasons I use and recommend the [i3 window manager][2] as an alternative Linux desktop experience.
In this post, I will walk through the installation and basic configuration of i3 on Fedora 28 Linux.
### 1\. Installation
Log into a Fedora workstation and open up a terminal. Use `dnf` to install the required package, like this:
```
[ricardo@f28i3 ~]$ sudo dnf install -y i3 i3-ipc i3status i3lock dmenu terminator --exclude=rxvt-unicode
Last metadata expiration check: 1:36:15 ago on Wed 08 Aug 2018 12:04:31 PM EDT.
Dependencies resolved.
================================================================================================
Package Arch Version Repository Size
================================================================================================
Installing:
dmenu x86_64 4.8-1.fc28 fedora 33 k
i3 x86_64 4.15-1.fc28 fedora 323 k
i3-ipc noarch 0.1.4-12.fc28 fedora 14 k
i3lock x86_64 2.9.1-2.fc28 fedora 33 k
i3status x86_64 2.12-1.fc28 updates 62 k
terminator noarch 1.91-4.fc28 fedora 570 k
Installing dependencies:
dzen2 x86_64 0.8.5-21.20100104svn.fc28 fedora 60 k
... Skipping dependencies/install messages
Complete!
[ricardo@f28i3 ~]$
```
**Note:** In this command, I'm explicitly excluding the package `rxvt-unicode` because I prefer `terminator` as my terminal emulator.
Depending on the status of your system, it may install many dependencies. Wait for the installation to complete successfully and then reboot your machine.
### 2. First login and initial setup
After your machine restarts, you're ready to log into i3 for the first time. In the GNOME Display Manager (GDM) screen, click on your username but—before typing the password to log in—click on the small gear icon and change the session to i3 instead of GNOME, like this:

Type your password and click `Sign In`. On your first login, you are presented with the i3 configuration screen:

Press `ENTER` to generate a config file in your `$HOME/.config/i3` directory. Later you can use this config file to further customize i3's behavior.
On the next screen, you need to select your `Mod` key. This is important, as the `Mod` key is used to trigger most of i3's keyboard shortcuts. Press `ENTER` to use the default `Win` key as the `Mod` key. If you don't have a `Win` key on your keyboard or prefer to use `Alt` instead, use the arrow key to select it and press `ENTER` to confirm.

You're now logged into your i3 session. Because i3 is a minimalist window manager, you see a black screen with the status bar on the bottom:

Next, let's look at navigating in i3.
### 3\. Basic shortcuts
Now that you're logged into an i3 session, you'll need a few basic keyboard shortcuts to get around.
The majority of i3 shortcuts use the `Mod` key you defined during the initial configuration. When I refer to `Mod` in the following examples, press the key you defined. This will usually be the `Win` key, but it can also be the `Alt` key.
First, to open up a terminal, use `Mod+ENTER`. Open more than one terminal and notice how i3 automatically tiles them to occupy all available space. By default, i3 splits the screen horizontally; use `Mod+v` to split vertically and press `Mod+h` to go back to the horizontal split.

To start other applications, press `Mod+d` to open `dmenu`, a simple text-based application menu. By default, `dmenu` presents a list of all applications available on your `$PATH`. Select the application you want to start by using the arrow keys or narrow down the search by typing parts of the application's name. Press `ENTER` to start the selected application.

If your application does not provide a way to close it, you can use i3 to kill a window by pressing `Mod+Shift+q`. Be careful, as you may lose unsaved work—this behavior depends on each application.
Finally, to end your session and exit i3, press `Mod+Shift+e`. You are presented with a confirmation message at the top of your screen. Click on `Yes, exit i3` to exit or `X` to cancel.

This is just an initial list of shortcuts you can use to get around i3. For many more, consult i3's official [documentation][3].
### 4\. Replacing GDM
Using i3 window manager reduces the memory utilization on your system; however, Fedora still uses the default GDM as its login screen. GDM loads several GNOME-related libraries and applications that consume memory.
If you want to further reduce your system's memory utilization, you can replace GDM with a more lightweight display manager, such as `lightdm`, like this:
```
[ricardo@f28i3 ~]$ sudo dnf install -y lightdm
[ricardo@f28i3 ~]$ sudo systemctl disable gdm
Removed /etc/systemd/system/display-manager.service.
[ricardo@f28i3 ~]$ sudo systemctl enable lightdm
Created symlink /etc/systemd/system/display-manager.service -> /usr/lib/systemd/system/lightdm.service.
[ricardo@f28i3 ~]$
```
Restart your machine to see the Lightdm login screen.
Now you're ready to log in and use i3.

--------------------------------------------------------------------------------
via: https://opensource.com/article/18/8/getting-started-i3-window-manager
作者:[Ricardo Gerardi][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/rgerardi
[1]: https://opensource.com/article/18/8/i3-tiling-window-manager
[2]: https://i3wm.org
[3]: https://i3wm.org/docs/userguide.html#_default_keybindings
|
Java
|
/*
* 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 2012-2020 the original author or authors.
*/
package org.assertj.core.api.long_;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual;
import org.assertj.core.api.LongAssert;
import org.assertj.core.api.LongAssertBaseTest;
import org.assertj.core.internal.Longs;
import org.assertj.core.internal.Objects;
import org.junit.jupiter.api.DisplayName;
/**
* Tests for <code>{@link LongAssert#usingDefaultComparator()}</code>.
*
* @author Joel Costigliola
*/
@DisplayName("LongAssert usingDefaultComparator")
class LongAssert_usingDefaultComparator_Test extends LongAssertBaseTest {
@Override
protected LongAssert invoke_api_method() {
return assertions.usingComparator(alwaysEqual()).usingDefaultComparator();
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions)).isSameAs(Objects.instance());
assertThat(getLongs(assertions)).isSameAs(Longs.instance());
}
}
|
Java
|
######################################################################
# tc_divmod.rb
#
# Test case for the Bignum#divmod instance method.
######################################################################
require 'test/unit'
class TC_Bignum_Divmod_InstanceMethod < Test::Unit::TestCase
def setup
@num_int = 9223372036854775808
@den_int = 8589934593
@num_flt = 9223372036854775808.0
@den_flt = 8589934593.0
end
def test_divmod_basic
assert_respond_to(@num_int, :divmod)
assert_nothing_raised{ @num_int.divmod(@den_int) }
assert_kind_of(Array, @num_int.divmod(@den_int))
end
def test_divmod_integers
assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_int))
assert_equal([0, 8589934593], @den_int.divmod(@num_int))
end
def test_divmod_integer_and_float
assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_int))
assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_flt))
end
def test_divmod_floats
assert_equal([1073741823, 7516192769.0], @num_flt.divmod(@den_flt))
assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_flt))
end
def test_divmod_expected_errors
assert_raises(ArgumentError){ @num_int.divmod }
assert_raises(ZeroDivisionError){ @num_int.divmod(0) }
assert_raises(TypeError){ @num_int.divmod(nil) }
assert_raises(TypeError){ @num_int.divmod('test') }
assert_raises(TypeError){ @num_int.divmod(true) }
end
def teardown
@num_int = nil
@den_int = nil
@num_flt = nil
@den_flt = nil
end
end
|
Java
|
/*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.testing.sanity;
import static com.evolveum.midpoint.prism.util.PrismAsserts.assertEqualsPolyString;
import static com.evolveum.midpoint.prism.util.PrismAsserts.assertParentConsistency;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty;
import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb;
import static com.evolveum.midpoint.test.IntegrationTestTools.getAttributeValues;
import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.path.ItemName;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.MapXNode;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.util.exception.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.opends.server.core.ModifyOperation;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.types.*;
import org.opends.server.types.ModificationType;
import org.opends.server.util.ChangeRecordEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.CapabilityUtil;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.SchemaTestConstants;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskExecutionStatus;
import com.evolveum.midpoint.test.Checker;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.test.ObjectChecker;
import com.evolveum.midpoint.test.ldap.OpenDJController;
import com.evolveum.midpoint.test.util.DerbyController;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectShadowChangeDescriptionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectTypeDefinitionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SchemaHandlingType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SelectorQualifiedGetOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectAlreadyExistsFaultType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType;
import com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType;
import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
/**
* Sanity test suite.
* <p/>
* It tests the very basic representative test cases. It does not try to be
* complete. It rather should be quick to execute and pass through the most
* representative cases. It should test all the system components except for
* GUI. Therefore the test cases are selected to pass through most of the
* components.
* <p/>
* It is using embedded H2 repository and embedded OpenDJ instance as a testing
* resource. The repository is instantiated from the Spring context in the
* same way as all other components. OpenDJ instance is started explicitly using
* BeforeClass method. Appropriate resource definition to reach the OpenDJ
* instance is provided in the test data and is inserted in the repository as
* part of test initialization.
*
* @author Radovan Semancik
*/
@ContextConfiguration(locations = {"classpath:ctx-sanity-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestSanity extends AbstractModelIntegrationTest {
private static final String REPO_DIR_NAME = "src/test/resources/repo/";
private static final String REQUEST_DIR_NAME = "src/test/resources/request/";
private static final File REQUEST_DIR = new File(REQUEST_DIR_NAME);
private static final String SYSTEM_CONFIGURATION_FILENAME = REPO_DIR_NAME + "system-configuration.xml";
private static final String SYSTEM_CONFIGURATION_OID = "00000000-0000-0000-0000-000000000001";
private static final String ROLE_SUPERUSER_FILENAME = REPO_DIR_NAME + "role-superuser.xml";
private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004";
private static final String RESOURCE_OPENDJ_FILENAME = REPO_DIR_NAME + "resource-opendj.xml";
private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff";
private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff";
protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson");
private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID";
private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn";
private static final String RESOURCE_DERBY_FILENAME = REPO_DIR_NAME + "resource-derby.xml";
private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab";
private static final String RESOURCE_BROKEN_FILENAME = REPO_DIR_NAME + "resource-broken.xml";
private static final String RESOURCE_BROKEN_OID = "ef2bc95b-76e0-59e2-ffff-ffffffffffff";
private static final String RESOURCE_DUMMY_FILENAME = REPO_DIR_NAME + "resource-dummy.xml";
private static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004";
private static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector";
private static final String CONNECTOR_DBTABLE_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-databasetable/org.identityconnectors.databasetable.DatabaseTableConnector";
private static final String CONNECTOR_BROKEN_FILENAME = REPO_DIR_NAME + "connector-broken.xml";
private static final String CONNECTOR_BROKEN_OID = "cccccccc-76e0-59e2-ffff-ffffffffffff";
private static final String TASK_OPENDJ_SYNC_FILENAME = REPO_DIR_NAME + "task-opendj-sync.xml";
private static final String TASK_OPENDJ_SYNC_OID = "91919191-76e0-59e2-86d6-3d4f02d3ffff";
private static final String TASK_USER_RECOMPUTE_FILENAME = REPO_DIR_NAME + "task-user-recompute.xml";
private static final String TASK_USER_RECOMPUTE_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaaa";
private static final String TASK_OPENDJ_RECON_FILENAME = REPO_DIR_NAME + "task-opendj-reconciliation.xml";
private static final String TASK_OPENDJ_RECON_OID = "91919191-76e0-59e2-86d6-3d4f02d30000";
private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = REPO_DIR_NAME + "sample-configuration-object.xml";
private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111";
private static final String USER_TEMPLATE_FILENAME = REPO_DIR_NAME + "user-template.xml";
private static final String USER_TEMPLATE_OID = "c0c010c0-d34d-b33f-f00d-777111111111";
private static final String USER_ADMINISTRATOR_FILENAME = REPO_DIR_NAME + "user-administrator.xml";
private static final String USER_ADMINISTRATOR_NAME = "administrator";
private static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002";
private static final String USER_JACK_FILENAME = REPO_DIR_NAME + "user-jack.xml";
private static final File USER_JACK_FILE = new File(USER_JACK_FILENAME);
private static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111";
private static final String USER_JACK_LDAP_UID = "jack";
private static final String USER_JACK_LDAP_DN = "uid=" + USER_JACK_LDAP_UID
+ "," + OPENDJ_PEOPLE_SUFFIX;
private static final String USER_GUYBRUSH_FILENAME = REPO_DIR_NAME + "user-guybrush.xml";
private static final File USER_GUYBRUSH_FILE = new File(USER_GUYBRUSH_FILENAME);
private static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111222";
private static final String USER_GUYBRUSH_USERNAME = "guybrush";
private static final String USER_GUYBRUSH_LDAP_UID = "guybrush";
private static final String USER_GUYBRUSH_LDAP_DN = "uid=" + USER_GUYBRUSH_LDAP_UID
+ "," + OPENDJ_PEOPLE_SUFFIX;
private static final String USER_E_LINK_ACTION_FILENAME = REPO_DIR_NAME + "user-e.xml";
private static final File USER_E_LINK_ACTION_FILE = new File(USER_E_LINK_ACTION_FILENAME);
private static final String LDIF_E_FILENAME_LINK = "src/test/resources/request/e-create.ldif";
private static final String ROLE_PIRATE_FILENAME = REPO_DIR_NAME + "role-pirate.xml";
private static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-987987987988";
private static final String ROLE_SAILOR_FILENAME = REPO_DIR_NAME + "role-sailor.xml";
private static final String ROLE_SAILOR_OID = "12345678-d34d-b33f-f00d-987955553535";
private static final String ROLE_CAPTAIN_FILENAME = REPO_DIR_NAME + "role-captain.xml";
private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc";
private static final String ROLE_JUDGE_FILENAME = REPO_DIR_NAME + "role-judge.xml";
private static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111";
private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account.xml";
private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account-derby.xml";
private static final String USER_JACK_DERBY_LOGIN = "jsparrow";
private static final String REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME = REQUEST_DIR_NAME + "user-modify-fullname-locality.xml";
private static final String REQUEST_USER_MODIFY_GIVENNAME_FILENAME = REQUEST_DIR_NAME + "user-modify-givenname.xml";
private static final String REQUEST_USER_MODIFY_PASSWORD_FILENAME = REQUEST_DIR_NAME + "user-modify-password.xml";
private static final String REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-disable.xml";
private static final String REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-enable.xml";
private static final String REQUEST_USER_MODIFY_NAME_FILENAME = REQUEST_DIR_NAME + "user-modify-name.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-pirate.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-1.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-2.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-judge.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-pirate.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-1.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-2.xml";
private static final File REQUEST_ACCOUNT_MODIFY_ATTRS_FILE = new File(REQUEST_DIR, "account-modify-attrs.xml");
private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE = new File(REQUEST_DIR, "account-modify-roomnumber.xml");
private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE = new File(REQUEST_DIR, "account-modify-roomnumber-explicit-type.xml");
private static final File REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE = new File(REQUEST_DIR, "account-modify-bad-path.xml");
private static final String LDIF_WILL_FILENAME = REQUEST_DIR_NAME + "will.ldif";
private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif");
private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif";
private static final String WILL_NAME = "wturner";
private static final String LDIF_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "angelika.ldif";
private static final String ANGELIKA_NAME = "angelika";
private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml";
private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif";
private static final String ELAINE_NAME = "elaine";
private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif");
private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif";
private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class);
private static final String NS_MY = "http://whatever.com/my";
private static final ItemName MY_SHIP_STATE = new ItemName(NS_MY, "shipState");
private static final ItemName MY_DEAD = new ItemName(NS_MY, "dead");
private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000;
/**
* Unmarshalled resource definition to reach the embedded OpenDJ instance.
* Used for convenience - the tests method may find it handy.
*/
private static ResourceType resourceTypeOpenDjrepo;
private static ResourceType resourceDerby;
private static String accountShadowOidOpendj;
private static String accountShadowOidDerby;
private static String accountShadowOidGuybrushOpendj;
private static String accountGuybrushOpendjEntryUuuid = null;
private static String originalJacksLdapPassword;
private static String lastJacksLdapPassword = null;
private int lastSyncToken;
@Autowired(required = true)
private MatchingRuleRegistry matchingRuleRegistry;
// This will get called from the superclass to init the repository
// It will be called only once
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
LOGGER.trace("initSystem");
try{
super.initSystem(initTask, initResult);
repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult);
repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult);
// This should discover the connectors
LOGGER.trace("initSystem: trying modelService.postInit()");
modelService.postInit(initResult);
LOGGER.trace("initSystem: modelService.postInit() done");
login(USER_ADMINISTRATOR_NAME);
// We need to add config after calling postInit() so it will not be applied.
// we want original logging configuration from the test logback config file, not
// the one from the system config.
repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult);
// Add broken connector before importing resources
repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult);
// Need to import instead of add, so the (dynamic) connector reference
// will be resolved
// correctly
importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult);
importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult);
repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult);
repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult);
repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult);
repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult);
repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult);
} catch (Exception ex){
LOGGER.error("erro: {}", ex);
throw ex;
}
}
/**
* Initialize embedded OpenDJ instance Note: this is not in the abstract
* superclass so individual tests may avoid starting OpenDJ.
*/
@Override
public void startResources() throws Exception {
openDJController.startCleanServer();
derbyController.startCleanServer();
}
/**
* Shutdown embedded OpenDJ instance Note: this is not in the abstract
* superclass so individual tests may avoid starting OpenDJ.
*/
@AfterClass
public static void stopResources() throws Exception {
openDJController.stop();
derbyController.stop();
}
/**
* Test integrity of the test setup.
*
* @throws SchemaException
* @throws ObjectNotFoundException
* @throws CommunicationException
*/
@Test
public void test000Integrity() throws Exception {
final String TEST_NAME = "test000Integrity";
TestUtil.displayTestTitle(this, TEST_NAME);
assertNotNull(modelWeb);
assertNotNull(modelService);
assertNotNull(repositoryService);
assertTrue(isSystemInitialized());
assertNotNull(taskManager);
assertNotNull(prismContext);
SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry();
assertNotNull(schemaRegistry);
// This is defined in extra schema. So this effectively checks whether the extra schema was loaded
PrismPropertyDefinition shipStateDefinition = schemaRegistry.findPropertyDefinitionByElementName(MY_SHIP_STATE);
assertNotNull("No my:shipState definition", shipStateDefinition);
assertEquals("Wrong maxOccurs in my:shipState definition", 1, shipStateDefinition.getMaxOccurs());
assertNoRepoCache();
Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test000Integrity");
OperationResult result = task.getResult();
// Check if OpenDJ resource was imported correctly
PrismObject<ResourceType> openDjResource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result);
display("Imported OpenDJ resource (repository)", openDjResource);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, openDjResource.getOid());
assertNoRepoCache();
String ldapConnectorOid = openDjResource.asObjectable().getConnectorRef().getOid();
PrismObject<ConnectorType> ldapConnector = repositoryService.getObject(ConnectorType.class, ldapConnectorOid, null, result);
display("LDAP Connector: ", ldapConnector);
// TODO: test if OpenDJ and Derby are running
repositoryService.getObject(GenericObjectType.class, SAMPLE_CONFIGURATION_OBJECT_OID, null, result);
}
/**
* Repeat self-test when we have all the dependencies on the classpath.
*/
@Test
public void test001SelfTests() throws Exception {
final String TEST_NAME = "test001SelfTests";
displayTestTitle(TEST_NAME);
// GIVEN
Task task = taskManager.createTaskInstance(TestSanity.class.getName()+"."+TEST_NAME);
// WHEN
OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task);
// THEN
assertSuccess("Repository self test", repositorySelfTestResult);
// WHEN
OperationResult provisioningSelfTestResult = modelDiagnosticService.provisioningSelfTest(task);
// THEN
display("Repository self test result", provisioningSelfTestResult);
// There may be warning about illegal key size on some platforms. As far as it is warning and not error we are OK
// the system will fall back to a interoperable key size
if (provisioningSelfTestResult.getStatus() != OperationResultStatus.SUCCESS && provisioningSelfTestResult.getStatus() != OperationResultStatus.WARNING) {
AssertJUnit.fail("Provisioning self-test failed: "+provisioningSelfTestResult);
}
}
/**
* Test the testResource method. Expect a complete success for now.
*/
@Test
public void test001TestConnectionOpenDJ() throws Exception {
final String TEST_NAME = "test001TestConnectionOpenDJ";
displayTestTitle(TEST_NAME);
// GIVEN
try{
assertNoRepoCache();
// WHEN
OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID);
// THEN
assertNoRepoCache();
displayJaxb("testResource result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("testResource has failed", result);
OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ");
PrismObject<ResourceType> resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult);
resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable();
assertNoRepoCache();
assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid());
display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo);
assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema());
Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo);
assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement);
PrismObject<ResourceType> openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID,
null, null, opResult);
display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig);
PrismObject<ResourceType> openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult);
display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel);
checkOpenDjResource(resourceTypeOpenDjrepo, "repository");
System.out.println("------------------------------------------------------------------");
display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo)));
System.out.println("------------------------------------------------------------------");
checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning");
checkOpenDjResource(openDjResourceModel.asObjectable(), "model");
// TODO: model web
} catch (Exception ex){
LOGGER.info("exception: " + ex);
throw ex;
}
}
private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result);
checkOpenDjResource(resource.asObjectable(), "repository");
}
/**
* Checks if the resource is internally consistent, if it has everything it should have.
*
* @throws SchemaException
*/
private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException {
assertNotNull("Resource from " + source + " is null", resource);
ObjectReferenceType connectorRefType = resource.getConnectorRef();
assertNotNull("Resource from " + source + " has null connectorRef", connectorRefType);
assertFalse("Resource from " + source + " has no OID in connectorRef", StringUtils.isBlank(connectorRefType.getOid()));
assertNotNull("Resource from " + source + " has null description in connectorRef", connectorRefType.getDescription());
assertNotNull("Resource from " + source + " has null filter in connectorRef", connectorRefType.getFilter());
assertNotNull("Resource from " + source + " has null filter element in connectorRef", connectorRefType.getFilter().getFilterClauseXNode());
assertNotNull("Resource from " + source + " has null configuration", resource.getConnectorConfiguration());
assertNotNull("Resource from " + source + " has null schema", resource.getSchema());
checkOpenDjSchema(resource, source);
assertNotNull("Resource from " + source + " has null schemahandling", resource.getSchemaHandling());
checkOpenDjSchemaHandling(resource, source);
if (!source.equals("repository")) {
// This is generated on the fly in provisioning
assertNotNull("Resource from " + source + " has null nativeCapabilities", resource.getCapabilities().getNative());
assertFalse("Resource from " + source + " has empty nativeCapabilities",
resource.getCapabilities().getNative().getAny().isEmpty());
}
assertNotNull("Resource from " + source + " has null configured capabilities", resource.getCapabilities().getConfigured());
assertFalse("Resource from " + source + " has empty capabilities", resource.getCapabilities().getConfigured().getAny().isEmpty());
assertNotNull("Resource from " + source + " has null synchronization", resource.getSynchronization());
checkOpenDjConfiguration(resource.asPrismObject(), source);
}
private void checkOpenDjSchema(ResourceType resource, String source) throws SchemaException {
ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext);
ObjectClassComplexTypeDefinition accountDefinition = schema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS);
assertNotNull("Schema does not define any account (resource from " + source + ")", accountDefinition);
Collection<? extends ResourceAttributeDefinition> identifiers = accountDefinition.getPrimaryIdentifiers();
assertFalse("No account identifiers (resource from " + source + ")", identifiers == null || identifiers.isEmpty());
// TODO: check for naming attributes and display names, etc
ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class);
if (capActivation != null && capActivation.getStatus() != null && capActivation.getStatus().getAttribute() != null) {
// There is simulated activation capability, check if the attribute is in schema.
QName enableAttrName = capActivation.getStatus().getAttribute();
ResourceAttributeDefinition enableAttrDef = accountDefinition.findAttributeDefinition(enableAttrName);
display("Simulated activation attribute definition", enableAttrDef);
assertNotNull("No definition for enable attribute " + enableAttrName + " in account (resource from " + source + ")", enableAttrDef);
assertTrue("Enable attribute " + enableAttrName + " is not ignored (resource from " + source + ")", enableAttrDef.isIgnored());
}
}
private void checkOpenDjSchemaHandling(ResourceType resource, String source) {
SchemaHandlingType schemaHandling = resource.getSchemaHandling();
for (ResourceObjectTypeDefinitionType resObjectTypeDef: schemaHandling.getObjectType()) {
if (resObjectTypeDef.getKind() == ShadowKindType.ACCOUNT) {
String name = resObjectTypeDef.getIntent();
assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig account definition without intent", name);
assertNotNull("Account type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass());
}
if (resObjectTypeDef.getKind() == ShadowKindType.ENTITLEMENT) {
String name = resObjectTypeDef.getIntent();
assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig entitlement definition without intent", name);
assertNotNull("Entitlement type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass());
}
}
}
private void checkOpenDjConfiguration(PrismObject<ResourceType> resource, String source) {
checkOpenResourceConfiguration(resource, CONNECTOR_LDAP_NAMESPACE, "bindPassword", 8, source);
}
private void checkOpenResourceConfiguration(PrismObject<ResourceType> resource, String connectorNamespace, String credentialsPropertyName,
int numConfigProps, String source) {
PrismContainer<Containerable> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION);
assertNotNull("No configuration container in "+resource+" from "+source, configurationContainer);
PrismContainer<Containerable> configPropsContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES);
assertNotNull("No configuration properties container in "+resource+" from "+source, configPropsContainer);
Collection<? extends Item<?,?>> configProps = configPropsContainer.getValue().getItems();
assertEquals("Wrong number of config properties in "+resource+" from "+source, numConfigProps, configProps.size());
PrismProperty<Object> credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace,credentialsPropertyName));
if (credentialsProp == null) {
// The is the heisenbug we are looking for. Just dump the entire damn thing.
display("Configuration with the heisenbug", configurationContainer.debugDump());
}
assertNotNull("No "+credentialsPropertyName+" property in "+resource+" from "+source, credentialsProp);
assertEquals("Wrong number of "+credentialsPropertyName+" property value in "+resource+" from "+source, 1, credentialsProp.getValues().size());
PrismPropertyValue<Object> credentialsPropertyValue = credentialsProp.getValues().iterator().next();
assertNotNull("No "+credentialsPropertyName+" property value in "+resource+" from "+source, credentialsPropertyValue);
if (credentialsPropertyValue.isRaw()) {
Object rawElement = credentialsPropertyValue.getRawElement();
assertTrue("Wrong element class "+rawElement.getClass()+" in "+resource+" from "+source, rawElement instanceof MapXNode);
// Element rawDomElement = (Element)rawElement;
MapXNode xmap = (MapXNode) rawElement;
try{
ProtectedStringType protectedType = new ProtectedStringType();
prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext());
// display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement));
// assertEquals("Wrong credentials element namespace in "+resource+" from "+source, connectorNamespace, rawDomElement.getNamespaceURI());
// assertEquals("Wrong credentials element local name in "+resource+" from "+source, credentialsPropertyName, rawDomElement.getLocalName());
// Element encryptedDataElement = DOMUtil.getChildElement(rawDomElement, new QName(DOMUtil.NS_XML_ENC, "EncryptedData"));
EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType();
assertNotNull("No EncryptedData element", encryptedDataType);
} catch (SchemaException ex){
throw new IllegalArgumentException(ex);
}
// assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI());
// assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName());
} else {
Object credentials = credentialsPropertyValue.getValue();
assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType);
ProtectedStringType credentialsPs = (ProtectedStringType)credentials;
EncryptedDataType encryptedData = credentialsPs.getEncryptedDataType();
assertNotNull("No EncryptedData element", encryptedData);
}
}
@Test
public void test002AddDerbyResource() throws Exception {
final String TEST_NAME = "test002AddDerbyResource";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME);
checkRepoOpenDjResource();
assertNoRepoCache();
PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DERBY_FILENAME));
assertParentConsistency(resource);
fillInConnectorRef(resource, IntegrationTestTools.DBTABLE_CONNECTOR_TYPE, result);
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<String> oidHolder = new Holder<>();
display("Adding Derby Resource", resource);
// WHEN
addObjectViaModelWS(resource.asObjectable(), null, oidHolder, resultHolder);
// THEN
// Check if Derby resource was imported correctly
PrismObject<ResourceType> derbyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result);
AssertJUnit.assertEquals(RESOURCE_DERBY_OID, derbyResource.getOid());
assertNoRepoCache();
String dbConnectorOid = derbyResource.asObjectable().getConnectorRef().getOid();
PrismObject<ConnectorType> dbConnector = repositoryService.getObject(ConnectorType.class, dbConnectorOid, null, result);
display("DB Connector: ", dbConnector);
// Check if password was encrypted during import
// via JAXB
Object configurationPropertiesElement = JAXBUtil.findElement(derbyResource.asObjectable().getConnectorConfiguration().getAny(),
new QName(dbConnector.asObjectable().getNamespace(), "configurationProperties"));
Object passwordElement = JAXBUtil.findElement(JAXBUtil.listChildElements(configurationPropertiesElement),
new QName(dbConnector.asObjectable().getNamespace(), "password"));
System.out.println("Password element: " + passwordElement);
// via prisms
PrismContainerValue configurationProperties = derbyResource.findContainer(
ItemPath.create(
ResourceType.F_CONNECTOR_CONFIGURATION,
new QName("configurationProperties")))
.getValue();
PrismProperty password = configurationProperties.findProperty(new ItemName(dbConnector.asObjectable().getNamespace(), "password"));
System.out.println("Password property: " + password);
}
private void addObjectViaModelWS(ObjectType objectType, ModelExecuteOptionsType options, Holder<String> oidHolder, Holder<OperationResultType> resultHolder) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
ObjectDeltaType objectDelta = new ObjectDeltaType();
objectDelta.setObjectToAdd(objectType);
QName type = objectType.asPrismObject().getDefinition().getTypeName();
objectDelta.setObjectType(type);
objectDelta.setChangeType(ChangeTypeType.ADD);
deltaList.getDelta().add(objectDelta);
ObjectDeltaOperationListType objectDeltaOperationListType = modelWeb.executeChanges(deltaList, options);
ObjectDeltaOperationType objectDeltaOperationType = getOdoFromDeltaOperationList(objectDeltaOperationListType, objectDelta);
resultHolder.value = objectDeltaOperationType.getExecutionResult();
oidHolder.value = ((ObjectType) objectDeltaOperationType.getObjectDelta().getObjectToAdd()).getOid();
}
// ugly hack...
private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDeltaOperationListType operationListType, ObjectDeltaType originalDelta) {
Validate.notNull(operationListType);
Validate.notNull(originalDelta);
for (ObjectDeltaOperationType operationType : operationListType.getDeltaOperation()) {
ObjectDeltaType objectDeltaType = operationType.getObjectDelta();
if (originalDelta.getChangeType() == ChangeTypeType.ADD) {
if (objectDeltaType.getChangeType() == originalDelta.getChangeType() &&
objectDeltaType.getObjectToAdd() != null) {
ObjectType objectAdded = (ObjectType) objectDeltaType.getObjectToAdd();
if (objectAdded.getClass().equals(originalDelta.getObjectToAdd().getClass())) {
return operationType;
}
}
} else {
if (objectDeltaType.getChangeType() == originalDelta.getChangeType() &&
originalDelta.getOid().equals(objectDeltaType.getOid())) {
return operationType;
}
}
}
throw new IllegalStateException("No suitable ObjectDeltaOperationType found");
}
private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoDerbyResource");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result);
checkDerbyResource(resource, "repository");
}
private void checkDerbyResource(PrismObject<ResourceType> resource, String source) {
checkDerbyConfiguration(resource, source);
}
private void checkDerbyConfiguration(PrismObject<ResourceType> resource, String source) {
checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source);
}
/**
* Test the testResource method. Expect a complete success for now.
*/
@Test
public void test003TestConnectionDerby() throws Exception {
TestUtil.displayTestTitle("test003TestConnectionDerby");
// GIVEN
checkRepoDerbyResource();
assertNoRepoCache();
// WHEN
OperationResultType result = modelWeb.testResource(RESOURCE_DERBY_OID);
// THEN
assertNoRepoCache();
displayJaxb("testResource result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("testResource has failed", result.getPartialResults().get(0));
OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test002TestConnectionDerby");
PrismObject<ResourceType> rObject = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, opResult);
resourceDerby = rObject.asObjectable();
checkDerbyResource(rObject, "repository(after test)");
assertNoRepoCache();
assertEquals(RESOURCE_DERBY_OID, resourceDerby.getOid());
display("Initialized Derby resource (respository)", resourceDerby);
assertNotNull("Resource schema was not generated", resourceDerby.getSchema());
Element resourceDerbyXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceDerby);
assertNotNull("Resource schema was not generated", resourceDerbyXsdSchemaElement);
PrismObject<ResourceType> derbyResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID,
null, null, opResult);
display("Initialized Derby resource (provisioning)", derbyResourceProvisioninig);
PrismObject<ResourceType> derbyResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID,
null, null, opResult);
display("Initialized Derby resource (model)", derbyResourceModel);
// TODO: check
// checkOpenDjResource(resourceOpenDj,"repository");
// checkOpenDjResource(openDjResourceProvisioninig,"provisioning");
// checkOpenDjResource(openDjResourceModel,"model");
// TODO: model web
}
@Test
public void test004Capabilities() throws ObjectNotFoundException, CommunicationException, SchemaException,
FaultMessage {
TestUtil.displayTestTitle("test004Capabilities");
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID,
options , objectHolder, resultHolder);
ResourceType resource = (ResourceType) objectHolder.value;
// THEN
display("Resource", resource);
assertNoRepoCache();
CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative();
List<Object> capabilities = nativeCapabilities.getAny();
assertFalse("Empty capabilities returned", capabilities.isEmpty());
for (Object capability : nativeCapabilities.getAny()) {
System.out.println("Native Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
if (resource.getCapabilities() != null) {
for (Object capability : resource.getCapabilities().getConfigured().getAny()) {
System.out.println("Configured Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
}
List<Object> effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource);
for (Object capability : effectiveCapabilities) {
System.out.println("Efective Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
CredentialsCapabilityType capCred = CapabilityUtil.getCapability(capabilities, CredentialsCapabilityType.class);
assertNotNull("password capability not present", capCred.getPassword());
// Connector cannot do activation, this should be null
ActivationCapabilityType capAct = CapabilityUtil.getCapability(capabilities, ActivationCapabilityType.class);
assertNull("Found activation capability while not expecting it", capAct);
capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class);
assertNotNull("password capability not found", capCred.getPassword());
// Although connector does not support activation, the resource specifies a way how to simulate it.
// Therefore the following should succeed
capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class);
assertNotNull("activation capability not found", capAct);
}
@Test
public void test005resolveConnectorRef() throws Exception{
TestUtil.displayTestTitle("test005resolveConnectorRef");
PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME));
ModelExecuteOptionsType options = new ModelExecuteOptionsType();
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>());
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ResourceType> uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult);
assertNotNull(uObject);
ResourceType resourceType = uObject.asObjectable();
assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef());
assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid());
}
@Test
public void test006reimportResourceDummy() throws Exception{
TestUtil.displayTestTitle("test006reimportResourceDummy");
//get object from repo (with version set and try to add it - it should be re-added, without error)
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult);
assertNotNull(resource);
ModelExecuteOptionsType options = new ModelExecuteOptionsType();
options.setOverwrite(Boolean.TRUE);
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>());
//TODO: add some asserts
//parse object from file again and try to add it - this should fail, becasue the same object already exists)
resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME));
try {
Holder<OperationResultType> resultHolder = new Holder<>();
options = new ModelExecuteOptionsType();
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(),
resultHolder);
OperationResultType result = resultHolder.value;
TestUtil.assertFailure(result);
fail("Expected object already exists exception, but haven't got one.");
} catch (FaultMessage ex) {
LOGGER.info("fault {}", ex.getFaultInfo());
LOGGER.info("fault {}", ex.getCause());
if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) {
// this is OK, we expect this
} else{
fail("Expected object already exists exception, but got: " + ex.getFaultInfo());
}
}
// ResourceType resourceType = uObject.asObjectable();
// assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef());
// assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid());
}
/**
* Attempt to add new user. It is only added to the repository, so check if
* it is in the repository after the operation.
*/
@Test
public void test010AddUser() throws Exception {
final String TEST_NAME = "test010AddUser";
displayTestTitle(TEST_NAME);
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_JACK_FILE);
UserType userType = user.asObjectable();
assertParentConsistency(user);
// Encrypt Jack's password
protector.encrypt(userType.getCredentials().getPassword().getValue());
assertParentConsistency(user);
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
display("Adding user object", userType);
// WHEN
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
// AssertJUnit.assertEquals(USER_JACK_OID, oid);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("repository.getObject result", repoResult);
TestUtil.assertSuccess("getObject has failed", repoResult);
AssertJUnit.assertEquals(USER_JACK_OID, repoUser.getOid());
assertEqualsPolyString("fullName", userType.getFullName(), repoUser.getFullName());
// TODO: better checks
}
/**
* Add account to user. This should result in account provisioning. Check if
* that happens in repo and in LDAP.
*/
@Test
public void test013AddOpenDjAccountToUser() throws Exception {
final String TEST_NAME = "test013AddOpenDjAccountToUser";
displayTestTitle(TEST_NAME);
try{
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
// IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE!
setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE);
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class);
// WHEN
displayWhen(TEST_NAME);
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals("No accountRefs", 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidOpendj = accountRef.getOid();
assertFalse(accountShadowOidOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
assertNotNull("Shadow stored in repository has no name", repoShadowType.getName());
// Check the "name" property, it should be set to DN, not entryUUID
assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "jack");
OpenDJController.assertAttribute(entry, "givenName", "Jack");
OpenDJController.assertAttribute(entry, "sn", "Sparrow");
OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow");
OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Black Pearl");
assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry));
originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", originalJacksLdapPassword);
System.out.println("password after create: " + originalJacksLdapPassword);
// Use getObject to test fetch of complete shadow
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl");
assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense"));
assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress"));
assertNotNull("Activation is null (model)", modelShadow.getActivation());
assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus());
} catch (Exception ex){
LOGGER.info("ERROR: {}", ex);
throw ex;
}
}
private OperationResultType modifyObjectViaModelWS(ObjectDeltaType objectChange) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
deltaList.getDelta().add(objectChange);
ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null);
return getOdoFromDeltaOperationList(list, objectChange).getExecutionResult();
}
/**
* Add Derby account to user. This should result in account provisioning. Check if
* that happens in repo and in Derby.
*/
@Test
public void test014AddDerbyAccountToUser() throws IOException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test014AddDerbyAccountToUser");
// GIVEN
checkRepoDerbyResource();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
// OpenDJ account was added in previous test, hence 2 accounts
assertEquals(2, accountRefs.size());
ObjectReferenceType accountRef = null;
for (ObjectReferenceType ref : accountRefs) {
if (!ref.getOid().equals(accountShadowOidOpendj)) {
accountRef = ref;
}
}
accountShadowOidDerby = accountRef.getOid();
assertFalse(accountShadowOidDerby.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidDerby,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("addObject has failed", repoResult);
display("Shadow (repository)", repoShadowType);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_DERBY_OID, repoShadowType.getResourceRef().getOid());
// Check the "name" property, it should be set to DN, not entryUUID
assertEquals("Wrong name property", PrismTestUtil.createPolyStringType(USER_JACK_DERBY_LOGIN),
repoShadowType.getName());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// check if account was created in DB Table
Statement stmt = derbyController.getExecutedStatementWhereLoginName(uid);
ResultSet rs = stmt.getResultSet();
System.out.println("RS: " + rs);
assertTrue("No records found for login name " + uid, rs.next());
assertEquals(USER_JACK_DERBY_LOGIN, rs.getString(DerbyController.COLUMN_LOGIN));
assertEquals("Cpt. Jack Sparrow", rs.getString(DerbyController.COLUMN_FULL_NAME));
// TODO: check password
//assertEquals("3lizab3th",rs.getString(DerbyController.COLUMN_PASSWORD));
System.out.println("Password: " + rs.getString(DerbyController.COLUMN_PASSWORD));
assertFalse("Too many records found for login name " + uid, rs.next());
rs.close();
stmt.close();
// Use getObject to test fetch of complete shadow
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType ();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_DERBY_OID, modelShadow.getResourceRef().getOid());
assertAttribute(modelShadow, SchemaConstants.ICFS_UID, USER_JACK_DERBY_LOGIN);
assertAttribute(modelShadow, SchemaConstants.ICFS_NAME, USER_JACK_DERBY_LOGIN);
assertAttribute(resourceDerby, modelShadow, "FULL_NAME", "Cpt. Jack Sparrow");
}
@Test
public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException {
TestUtil.displayTestTitle("test015AccountOwner");
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<UserType> userHolder = new Holder<>();
// WHEN
modelWeb.findShadowOwner(accountShadowOidOpendj, userHolder, resultHolder);
// THEN
display("listAccountShadowOwner result", resultHolder.value);
TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value);
UserType user = userHolder.value;
assertNotNull("No owner", user);
assertEquals(USER_JACK_OID, user.getOid());
System.out.println("Account " + accountShadowOidOpendj + " has owner " + ObjectTypeUtil.toShortString(user));
}
@Test
public void test016ProvisioningSearchAccountsIterative() throws Exception {
TestUtil.displayTestTitle("test016ProvisioningSearchAccountsIterative");
// GIVEN
OperationResult result = new OperationResult(TestSanity.class.getName() + ".test016ProvisioningSearchAccountsIterative");
RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceTypeOpenDjrepo, prismContext);
final RefinedObjectClassDefinition refinedAccountDefinition = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT);
QName objectClass = refinedAccountDefinition.getObjectClassDefinition().getTypeName();
ObjectQuery q = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceTypeOpenDjrepo.getOid(), objectClass, prismContext);
final Collection<ObjectType> objects = new HashSet<>();
final MatchingRule caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME, DOMUtil.XSD_STRING);
ResultHandler handler = new ResultHandler<ObjectType>() {
@Override
public boolean handle(PrismObject<ObjectType> prismObject, OperationResult parentResult) {
ObjectType objectType = prismObject.asObjectable();
objects.add(objectType);
display("Found object", objectType);
assertTrue(objectType instanceof ShadowType);
ShadowType shadow = (ShadowType) objectType;
assertNotNull(shadow.getOid());
assertNotNull(shadow.getName());
assertEquals(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, shadow.getObjectClass());
assertEquals(RESOURCE_OPENDJ_OID, shadow.getResourceRef().getOid());
String icfUid = getAttributeValue(shadow, getOpenDjPrimaryIdentifierQName());
assertNotNull("No ICF UID", icfUid);
String icfName = getNormalizedAttributeValue(shadow, refinedAccountDefinition, getOpenDjSecondaryIdentifierQName());
assertNotNull("No ICF NAME", icfName);
try {
PrismAsserts.assertEquals("Wrong shadow name", caseIgnoreMatchingRule, shadow.getName().getOrig(), icfName);
} catch (SchemaException e) {
throw new IllegalArgumentException(e.getMessage(),e);
}
assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "uid")));
assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "cn")));
assertNotNull("Missing LDAP sn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "sn")));
assertNotNull("Missing activation", shadow.getActivation());
assertNotNull("Missing activation status", shadow.getActivation().getAdministrativeStatus());
return true;
}
};
// WHEN
provisioningService.searchObjectsIterative(ShadowType.class, q, null, handler, null, result);
// THEN
display("Count", objects.size());
}
/**
* We are going to modify the user. As the user has an account, the user
* changes should be also applied to the account (by schemaHandling).
*/
@Test
public void test020ModifyUser() throws Exception {
final String TEST_NAME = "test020ModifyUser";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong value for locality", "somewhere", repoUserType.getLocality());
assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUserType,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
assertOpenDJAccountJack(uid, "jack");
}
private Entry assertOpenDJAccountJack(String entryUuid, String uid) throws DirectoryException {
Entry entry = openDJController.searchAndAssertByEntryUuid(entryUuid);
return assertOpenDJAccountJack(entry, uid);
}
private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryException {
return assertOpenDJAccountJack(entry, uid, "Jack");
}
private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException {
display(entry);
OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com");
OpenDJController.assertAttribute(entry, "uid", uid);
if (givenName == null) {
OpenDJController.assertAttribute(entry, "givenName");
} else {
OpenDJController.assertAttribute(entry, "givenName", givenName);
}
OpenDJController.assertAttribute(entry, "sn", "Sparrow");
// These two should be assigned from the User modification by
// schemaHandling
OpenDJController.assertAttribute(entry, "cn", "Cpt. Jack Sparrow");
OpenDJController.assertAttribute(entry, "displayName", "Cpt. Jack Sparrow");
// This will get translated from "somewhere" to this (outbound
// expression in schemeHandling) -> this is not more supported...we
// don't support complex run-time properties. the value will be
// evaluated from outbound expression
OpenDJController.assertAttribute(entry, "l", "somewhere");
OpenDJController.assertAttribute(entry, "postalAddress", "Number 1");
return entry;
}
/**
* We are going to change user's password. As the user has an account, the password change
* should be also applied to the account (by schemaHandling).
*/
@Test
public void test022ChangeUserPassword() throws Exception {
final String TEST_NAME = "test022ChangeUserPassword";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_PASSWORD_FILENAME, ObjectDeltaType.class);
System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0));
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertUserPasswordChange("butUnd3dM4yT4lkAL0t", result);
}
/**
* Similar to previous test just the request is constructed a bit differently.
*/
@Test
public void test023ChangeUserPasswordJAXB() throws Exception {
final String TEST_NAME = "test023ChangeUserPasswordJAXB";
displayTestTitle(TEST_NAME);
// GIVEN
final String NEW_PASSWORD = "abandonSHIP";
Document doc = ModelClientUtil.getDocumnent();
ObjectDeltaType userDelta = new ObjectDeltaType();
userDelta.setOid(USER_JACK_OID);
userDelta.setChangeType(ChangeTypeType.MODIFY);
userDelta.setObjectType(UserType.COMPLEX_TYPE);
ItemDeltaType passwordDelta = new ItemDeltaType();
passwordDelta.setModificationType(ModificationTypeType.REPLACE);
passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext));
ProtectedStringType pass = new ProtectedStringType();
pass.setClearValue(NEW_PASSWORD);
XNode passValue = prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(pass).getSubnode();
System.out.println("PASSWORD VALUE: " + passValue.debugDump());
RawType passwordValue = new RawType(passValue, prismContext);
passwordDelta.getValue().add(passwordValue);
userDelta.getItemDelta().add(passwordDelta);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(userDelta);
// THEN
assertUserPasswordChange(NEW_PASSWORD, result);
}
private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException {
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
// Check if nothing else was modified
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality());
// Check if appropriate accountRef is still there
assertLinks(repoUser, 2);
assertLinked(repoUser, accountShadowOidOpendj);
assertLinked(repoUser, accountShadowOidDerby);
assertPassword(repoUser, expectedUserPassword);
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
display("repository shadow", repoShadow);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry entry = assertOpenDJAccountJack(uid, "jack");
String ldapPasswordAfter = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull(ldapPasswordAfter);
display("LDAP password after change", ldapPasswordAfter);
assertFalse("No change in password (original)", ldapPasswordAfter.equals(originalJacksLdapPassword));
if (lastJacksLdapPassword != null) {
assertFalse("No change in password (last)", ldapPasswordAfter.equals(lastJacksLdapPassword));
}
lastJacksLdapPassword = ldapPasswordAfter;
}
@Test
public void test027ModifyAccountDj() throws Exception {
final String TEST_NAME = "test027ModifyAccountDj";
testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck");
}
@Test
public void test028ModifyAccountDjExplicitType() throws Exception {
final String TEST_NAME = "test028ModifyAccountDjExplicitType";
testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck");
}
public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception {
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(reqFile, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidOpendj);
// WHEN
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack");
OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal);
}
@Test
public void test029ModifyAccountDjBadPath() throws Exception {
final String TEST_NAME = "test029ModifyAccountDjBadPath";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidOpendj);
OperationResultType result;
try {
// WHEN
result = modifyObjectViaModelWS(objectChange);
AssertJUnit.fail("Unexpected success");
} catch (FaultMessage f) {
// this is expected
FaultType faultInfo = f.getFaultInfo();
result = faultInfo.getOperationResult();
}
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertFailure(result);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack");
OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", "upperdeck");
}
/**
* Try to disable user. As the user has an account, the account should be disabled as well.
*/
@Test
public void test030DisableUser() throws Exception {
final String TEST_NAME = "test030DisableUser";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class);
Entry entry = openDJController.searchByUid("jack");
assertOpenDJAccountJack(entry, "jack");
String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
display("ds-pwp-account-disabled before change", pwpAccountDisabled);
assertTrue("LDAP account is not enabled (precondition)", openDJController.isAccountEnabled(entry));
assertNoRepoCache();
// WHEN
displayWhen(TEST_NAME);
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
display("repository user", repoUser);
UserType repoUserType = repoUser.asObjectable();
// Check if nothing else was modified
assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUserType,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
display("repo shadow", repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jack");
pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
display("ds-pwp-account-disabled after change", pwpAccountDisabled);
assertFalse("LDAP account was not disabled", openDJController.isAccountEnabled(entry));
// Use getObject to test fetch of complete shadow
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
// WHEN
displayWhen(TEST_NAME);
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere");
assertNotNull("The account activation is null in the shadow", modelShadow.getActivation());
assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus());
assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, modelShadow.getActivation().getAdministrativeStatus());
}
/**
* Try to enable user after it has been disabled. As the user has an account, the account should be enabled as well.
*/
@Test
public void test031EnableUser() throws Exception {
final String TEST_NAME = "test031EnableUser";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class);
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
display("repo user", repoUser);
// Check if nothing else was modified
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUser.getFullName());
PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUser.getLocality());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUser,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repo shadow", repoShadowType);
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Use getObject to test fetch of complete shadow
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere");
assertNotNull("The account activation is null in the shadow", modelShadow.getActivation());
assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus());
assertEquals("The account was not enabled in the shadow", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus());
// Check if LDAP account was updated
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jack");
// The value of ds-pwp-account-disabled should have been removed
String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
System.out.println("ds-pwp-account-disabled after change: " + pwpAccountDisabled);
assertTrue("LDAP account was not enabled", openDJController.isAccountEnabled(entry));
}
/**
* Unlink account by removing the accountRef from the user.
* The account will not be deleted, just the association to user will be broken.
*/
@Test
public void test040UnlinkDerbyAccountFromUser() throws FileNotFoundException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test040UnlinkDerbyAccountFromUser");
// GIVEN
ObjectDeltaType objectChange = new ObjectDeltaType();
objectChange.setOid(USER_JACK_OID);
ItemDeltaType modificationDeleteAccountRef = new ItemDeltaType();
modificationDeleteAccountRef.setModificationType(ModificationTypeType.DELETE);
ObjectReferenceType accountRefToDelete = new ObjectReferenceType();
accountRefToDelete.setOid(accountShadowOidDerby);
RawType modificationValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(accountRefToDelete).getSubnode(), prismContext);
modificationDeleteAccountRef.getValue().add(modificationValue);
modificationDeleteAccountRef.setPath(new ItemPathType(UserType.F_LINK_REF));
objectChange.getItemDelta().add(modificationDeleteAccountRef);
objectChange.setChangeType(ChangeTypeType.MODIFY);
objectChange.setObjectType(UserType.COMPLEX_TYPE);
displayJaxb("modifyObject input", objectChange, new QName(SchemaConstants.NS_C, "change"));
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
// only OpenDJ account should be left now
assertEquals(1, accountRefs.size());
ObjectReferenceType ref = accountRefs.get(0);
assertEquals("Wrong OID in accountRef in "+repoUser, accountShadowOidOpendj, ref.getOid());
}
/**
* Delete the shadow which will cause deletion of associated account.
* The account was unlinked in the previous test, therefore no operation with user is needed.
*/
@Test
public void test041DeleteDerbyAccount() throws FileNotFoundException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test041DeleteDerbyAccount");
// GIVEN
assertNoRepoCache();
// WHEN
OperationResultType result = deleteObjectViaModelWS(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby);
// THEN
assertNoRepoCache();
displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("deleteObject has failed", result);
// Check if shadow was deleted
OperationResult repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(ShadowType.class, accountShadowOidDerby,
null, repoResult);
AssertJUnit.fail("Shadow was not deleted");
} catch (ObjectNotFoundException ex) {
display("Caught expected exception from getObject(shadow): " + ex);
}
// check if account was deleted in DB Table
Statement stmt = derbyController.getExecutedStatementWhereLoginName(USER_JACK_DERBY_LOGIN);
ResultSet rs = stmt.getResultSet();
System.out.println("RS: " + rs);
assertFalse("Account was not deleted in database", rs.next());
}
private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
ObjectDeltaType objectDelta = new ObjectDeltaType();
objectDelta.setOid(oid);
objectDelta.setObjectType(typeQName);
objectDelta.setChangeType(ChangeTypeType.DELETE);
deltaList.getDelta().add(objectDelta);
ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null);
return getOdoFromDeltaOperationList(list, objectDelta).getExecutionResult();
}
@Test
public void test047RenameUser() throws Exception {
final String TEST_NAME = "test047RenameUser";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for User name", "jsparrow", repoUserType.getName());
PrismAsserts.assertEqualsPolyString("wrong value for User fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong value for User locality", "somewhere", repoUserType.getLocality());
assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.iterator().next();
assertEquals("Wrong OID in "+accountRef+" in "+repoUserType,
accountShadowOidOpendj, accountRef.getOid());
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
assertOpenDJAccountJack(uid, "jsparrow");
}
/**
* We are going to modify the user. As the user has an account, the user
* changes should be also applied to the account (by schemaHandling).
*
* @throws DirectoryException
*/
@Test
public void test048ModifyUserRemoveGivenName() throws Exception {
final String TEST_NAME = "test048ModifyUserRemoveGivenName";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class);
displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
assertNull("Value for givenName still present", repoUserType.getGivenName());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.iterator().next();
accountRef.getOid().equals(accountShadowOidOpendj);
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jsparrow", null);
}
/**
* The user should have an account now. Let's try to delete the user. The
* account should be gone as well.
*
* @throws JAXBException
*/
@Test
public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException, JAXBException {
TestUtil.displayTestTitle("test049DeleteUser");
// GIVEN
assertNoRepoCache();
// WHEN
OperationResultType result = deleteObjectViaModelWS(ObjectTypes.USER.getTypeQName(), USER_JACK_OID);
// THEN
assertNoRepoCache();
displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("deleteObject has failed", result);
// User should be gone from the repository
OperationResult repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
AssertJUnit.fail("User still exists in repo after delete");
} catch (ObjectNotFoundException e) {
// This is expected
}
// Account shadow should be gone from the repository
repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
AssertJUnit.fail("Shadow still exists in repo after delete");
} catch (ObjectNotFoundException e) {
// This is expected, but check also the result
AssertJUnit.assertFalse("getObject failed as expected, but the result indicates success",
repoResult.isSuccess());
}
// Account should be deleted from LDAP
InternalSearchOperation op = openDJController.getInternalConnection().processSearch(
"dc=example,dc=com", SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100,
100, false, "(uid=" + USER_JACK_LDAP_UID + ")", null);
AssertJUnit.assertEquals(0, op.getEntriesSent());
}
@Test
public void test100AssignRolePirate() throws Exception {
final String TEST_NAME = "test100AssignRolePirate";
displayTestTitle(TEST_NAME);
// GIVEN
// IMPORTANT! Assignment enforcement is FULL now
setAssignmentEnforcement(AssignmentPolicyEnforcementType.FULL);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.FULL);
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_GUYBRUSH_FILE);
UserType userType = user.asObjectable();
// Encrypt the password
protector.encrypt(userType.getCredentials().getPassword().getValue());
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
assertNoRepoCache();
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
assertNoRepoCache();
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadowType);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
// TODO: Derby
}
@Test
public void test101AccountOwnerAfterRole() throws Exception {
final String TEST_NAME = "test101AccountOwnerAfterRole";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<UserType> userHolder = new Holder<>();
// WHEN
modelWeb.findShadowOwner(accountShadowOidGuybrushOpendj, userHolder, resultHolder);
// THEN
TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value);
UserType user = userHolder.value;
assertNotNull("No owner", user);
assertEquals(USER_GUYBRUSH_OID, user.getOid());
System.out.println("Account " + accountShadowOidGuybrushOpendj + " has owner " + ObjectTypeUtil.toShortString(user));
}
@Test
public void test102AssignRoleCaptain() throws Exception {
final String TEST_NAME = "test102AssignRoleCaptain";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignment
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
/**
* Assign the same "captain" role again, this time with a slightly different assignment parameters.
*/
@Test
public void test103AssignRoleCaptainAgain() throws Exception {
final String TEST_NAME = "test103AssignRoleCaptainAgain";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
@Test
public void test105ModifyAccount() throws Exception {
final String TEST_NAME = "test105ModifyAccount";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidGuybrushOpendj);
// WHEN ObjectTypes.SHADOW.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
Task task = taskManager.createTaskInstance();
OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify");
PrismObject<ShadowType> shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult);
assertNotNull("shadow must not be null", shadow);
ShadowType shadowType = shadow.asObjectable();
QName employeeTypeQName = new QName(resourceTypeOpenDjrepo.getNamespace(), "employeeType");
ItemPath employeeTypePath = ItemPath.create(ShadowType.F_ATTRIBUTES, employeeTypeQName);
PrismProperty item = shadow.findProperty(employeeTypePath);
PropertyDelta deleteDelta = prismContext.deltaFactory().property().create(ShadowType.F_ATTRIBUTES, item.getDefinition().getItemName(), item.getDefinition());
// PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition());
// PrismPropertyValue valToDelte = new PrismPropertyValue("A");
// valToDelte.setParent(deleteDelta);
Collection<PrismPropertyValue> values= item.getValues();
for (PrismPropertyValue val : values){
if ("A".equals(val.getValue())){
deleteDelta.addValueToDelete(val.clone());
}
}
ObjectDelta delta = prismContext.deltaFactory().object().create(ShadowType.class, ChangeType.MODIFY);
delta.addModification(deleteDelta);
delta.setOid(accountShadowOidGuybrushOpendj);
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
deltas.add(delta);
LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------");
modelService.executeChanges(deltas, null, task, parentResult);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// check if LDAP account was modified
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
OpenDJController.assertAttribute(entry, "roomNumber", "captain's cabin");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
}
/**
* Judge role excludes pirate role. This assignment should fail.
*/
@Test
public void test104AssignRoleJudge() throws Exception {
final String TEST_NAME = "test104AssignRoleJudge";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class);
try {
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
AssertJUnit.fail("Expected a failure after assigning conflicting roles but nothing happened and life goes on");
} catch (FaultMessage f) {
// This is expected
// TODO: check if the fault is the right one
}
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object remain unmodified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Unexpected number or accountRefs", 1, accountRefs.size());
}
@Test
public void test107UnassignRolePirate() throws Exception {
final String TEST_NAME = "test107UnassignRolePirate";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
@Test
public void test108UnassignRoleCaptain() throws Exception {
final String TEST_NAME = "test108UnassignRoleCaptain";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
/**
* Captain role was assigned twice. It has to also be unassigned twice.
*/
@Test
public void test109UnassignRoleCaptainAgain() throws Exception {
final String TEST_NAME = "test109UnassignRoleCaptainAgain";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
//TODO TODO TODO TODO operation result from repostiory.getObject is unknown...find out why..
// assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PropertyReferenceListType resolve = new PropertyReferenceListType();
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUserType);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(0, accountRefs.size());
// Check if shadow was deleted from the repo
repoResult = new OperationResult("getObject");
try {
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
AssertJUnit.fail("Account shadow was not deleted from repo");
} catch (ObjectNotFoundException ex) {
// This is expected
}
// check if account was deleted from LDAP
Entry entry = openDJController.searchByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
assertNull("LDAP account was not deleted", entry);
// TODO: Derby
}
// Synchronization tests
/**
* Test initialization of synchronization. It will create a cycle task and
* check if the cycle executes No changes are synchronized yet.
*/
@Test
public void test300LiveSyncInit() throws Exception {
final String TEST_NAME = "test300LiveSyncInit";
displayTestTitle(TEST_NAME);
// Now it is the right time to add task definition to the repository
// We don't want it there any sooner, as it may interfere with the
// previous tests
checkAllShadows();
// IMPORTANT! Assignment enforcement is POSITIVE now
setAssignmentEnforcement(AssignmentPolicyEnforcementType.POSITIVE);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task manager to pick up the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
display("Task while waiting for task manager to pick up the task", task);
// wait until the task is picked up
return task.getLastRunFinishTimestamp() != null;
// if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) {
// // wait until the first run is finished
// if (task.getLastRunFinishTimestamp() == null) {
// return false;
// }
// return true;
// }
// return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 20000);
// Check task status
Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, retrieveTaskResult(), result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after pickup", task);
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_SYNC_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and claimed
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
// .. and last run should not be zero
assertNotNull("No lastRunStartTimestamp", task.getLastRunStartTimestamp());
assertFalse("Zero lastRunStartTimestamp", task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull("No lastRunFinishedTimestamp", task.getLastRunFinishTimestamp());
assertFalse("Zero lastRunFinishedTimestamp", task.getLastRunFinishTimestamp().longValue() == 0);
// Test for extension. This will also roughly test extension processor
// and schema processor
PrismContainer<?> taskExtension = task.getExtensionOrClone();
AssertJUnit.assertNotNull(taskExtension);
display("Task extension", taskExtension);
PrismProperty<String> shipStateProp = taskExtension.findProperty(MY_SHIP_STATE);
AssertJUnit.assertEquals("Wrong 'shipState' property value", "capsized", shipStateProp.getValue().getValue());
PrismProperty<Integer> deadProp = taskExtension.findProperty(MY_DEAD);
PrismPropertyValue<Integer> deadPVal = deadProp.getValues().iterator().next();
AssertJUnit.assertEquals("Wrong 'dead' property class", Integer.class, deadPVal.getValue().getClass());
AssertJUnit.assertEquals("Wrong 'dead' property value", Integer.valueOf(42), deadPVal.getValue());
// The progress should be 0, as there were no changes yet
AssertJUnit.assertEquals(0, task.getProgress());
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull(taskResult);
assertTrue("Task result is not a success, it is "+taskResult, taskResult.isSuccess());
final Object tokenAfter = findSyncToken(task);
display("Sync token after", tokenAfter.toString());
lastSyncToken = (Integer)tokenAfter;
checkAllShadows();
// Try without options. The results should NOT be there
// MID-4670
task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result);
taskResult = task.getResult();
AssertJUnit.assertNull("Unexpected task result", taskResult);
}
/**
* Create LDAP object. That should be picked up by liveSync and a user
* should be created in repo.
*/
@Test
public void test301LiveSyncCreate() throws Exception {
final String TEST_NAME = "test301LiveSyncCreate";
displayTestTitle(TEST_NAME);
// Sync task should be running (tested in previous test), so just create
// new LDAP object.
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
final Object tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore.toString());
// WHEN
displayWhen(TEST_NAME);
Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_FILENAME);
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 2, result);
// THEN
displayThen(TEST_NAME);
// Search for the user that should be created now
UserType user = searchUserByName(WILL_NAME);
PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName());
assertNotNull(user.getLinkRef());
assertFalse(user.getLinkRef().isEmpty());
// AssertJUnit.assertEquals(user.getName(), WILL_NAME);
// TODO: more checks
assertAndStoreSyncTokenIncrement(syncCycle, 2);
checkAllShadows();
}
@Test
public void test302LiveSyncModify() throws Exception {
final String TEST_NAME = "test302LiveSyncModify";
displayTestTitle(TEST_NAME);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
// WHEN
display("Modifying LDAP entry");
ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_WILL_MODIFY_FILE);
// THEN
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result);
// Search for the user that should be created now
UserType user = searchUserByName (WILL_NAME);
// AssertJUnit.assertEquals(WILL_NAME, user.getName());
PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName());
PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName());
assertAndStoreSyncTokenIncrement(syncCycle, 1);
checkAllShadows();
}
@Test
public void test303LiveSyncLink() throws Exception {
final String TEST_NAME = "test303LiveSyncLink";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE);
UserType userType = user.asObjectable();
final String userOid = userType.getOid();
// Encrypt e's password
protector.encrypt(userType.getCredentials().getPassword().getValue());
// create user in repository
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<String> oidHolder = new Holder<>();
display("Adding user object", userType);
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
//check results
assertNoRepoCache();
displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
// AssertJUnit.assertEquals(userOid, oidHolder.value);
//WHEN
displayWhen(TEST_NAME);
//create account for e which should be correlated
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
Entry entry = openDJController.addEntryFromLdifFile(LDIF_E_FILENAME_LINK);
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result);
// THEN
displayThen(TEST_NAME);
//check user and account ref
userType = searchUserByName("e");
List<ObjectReferenceType> accountRefs = userType.getLinkRef();
assertEquals("Account ref not found, or found too many", 1, accountRefs.size());
//check account defined by account ref
String accountOid = accountRefs.get(0).getOid();
ShadowType account = searchAccountByOid(accountOid);
assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName());
assertAndStoreSyncTokenIncrement(syncCycle, 1);
checkAllShadows();
}
/**
* Create LDAP object. That should be picked up by liveSync and a user
* should be created in repo.
* Also location (ldap l) should be updated through outbound
*/
@Test
public void test304LiveSyncCreateNoLocation() throws Exception {
final String TEST_NAME = "test304LiveSyncCreateNoLocation";
displayTestTitle(TEST_NAME);
// Sync task should be running (tested in previous test), so just create
// new LDAP object.
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
// WHEN
Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_WITHOUT_LOCATION_FILENAME);
display("Entry from LDIF", entry);
// THEN
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 3, result, 60000);
// Search for the user that should be created now
final String userName = "wturner1";
UserType user = searchUserByName(userName);
List<ObjectReferenceType> accountRefs = user.getLinkRef();
assertEquals("Account ref not found, or found too many", 1, accountRefs.size());
//check account defined by account ref
String accountOid = accountRefs.get(0).getOid();
ShadowType account = searchAccountByOid(accountOid);
assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName());
// assertEquals("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName());
Collection<String> localities = getAttributeValues(account, new QName(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS.getNamespaceURI(), "l"));
assertNotNull("null value list for attribute 'l'", localities);
assertEquals("unexpected number of values of attribute 'l'", 1, localities.size());
assertEquals("Locality doesn't match", "middle of nowhere", localities.iterator().next());
assertAndStoreSyncTokenIncrement(syncCycle, 3);
checkAllShadows();
}
private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) {
final Object tokenAfter = findSyncToken(syncCycle);
display("Sync token after", tokenAfter.toString());
int tokenAfterInt = (Integer)tokenAfter;
int expectedToken = lastSyncToken + increment;
lastSyncToken = tokenAfterInt;
assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt);
}
private int findSyncToken(Task syncCycle) {
return (Integer)findSyncTokenObject(syncCycle);
}
private Object findSyncTokenObject(Task syncCycle) {
Object token = null;
PrismProperty<?> tokenProperty = syncCycle.getExtensionOrClone().findProperty(SchemaConstants.SYNC_TOKEN);
if (tokenProperty != null) {
Collection<?> values = tokenProperty.getRealValues();
if (values.size() > 1) {
throw new IllegalStateException("Too must values in token "+tokenProperty);
}
token = values.iterator().next();
}
return token;
}
/**
* Not really a test. Just cleans up after live sync.
*/
@Test
public void test399LiveSyncCleanup() throws Exception {
final String TEST_NAME = "test399LiveSyncCleanup";
displayTestTitle(TEST_NAME);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result);
// TODO: check if the task is really stopped
}
@Test
public void test400ImportFromResource() throws Exception {
final String TEST_NAME = "test400ImportFromResource";
displayTestTitle(TEST_NAME);
// GIVEN
checkAllShadows();
assertNoRepoCache();
OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting
ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE);
display("Entry from LDIF", entry);
// Let's add an entry with multiple uids.
Entry addEntry = openDJController.addEntryFromLdifFile(LDIF_HERMAN_FILENAME);
display("Entry from LDIF", addEntry);
// WHEN
displayWhen(TEST_NAME);
TaskType taskType = modelWeb.importFromResource(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("importFromResource result", taskType.getResult(), SchemaConstants.C_RESULT);
AssertJUnit.assertEquals("importFromResource has failed", OperationResultStatusType.IN_PROGRESS, taskType.getResult().getStatus());
// Convert the returned TaskType to a more usable Task
Task task = taskManager.createTaskInstance(taskType.asPrismObject(), result);
AssertJUnit.assertNotNull(task);
assertNotNull(task.getOid());
AssertJUnit.assertTrue(task.isAsynchronous());
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
display("Import task after launch", task);
PrismObject<TaskType> tObject = repositoryService.getObject(TaskType.class, task.getOid(), null, result);
TaskType taskAfter = tObject.asObjectable();
display("Import task in repo after launch", taskAfter);
result.computeStatus();
TestUtil.assertSuccess("getObject has failed", result);
final String taskOid = task.getOid();
waitFor("Waiting for import to complete", new Checker() {
@Override
public boolean check() throws CommonException {
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
OperationResult opResult = new OperationResult("import check");
assertNoRepoCache();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
try {
modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), taskOid,
options, objectHolder, resultHolder);
} catch (FaultMessage faultMessage) {
throw new SystemException(faultMessage);
}
assertNoRepoCache();
// display("getObject result (wait loop)",resultHolder.value);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
Task task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), opResult);
System.out.println(new Date() + ": Import task status: " + task.getExecutionStatus() + ", progress: " + task.getProgress());
if (task.getExecutionStatus() == TaskExecutionStatus.CLOSED) {
// Task closed, wait finished
return true;
}
// IntegrationTestTools.display("Task result while waiting: ", task.getResult());
return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 180000);
// wait a second until the task will be definitely saved
Thread.sleep(1000);
//### Check task state after the task is finished ###
Holder<ObjectType> objectHolder = new Holder<>();
Holder<OperationResultType> resultHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), task.getOid(),
options, objectHolder, resultHolder);
assertNoRepoCache();
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), result);
display("Import task after finish (fetched from model)", task);
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp());
assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp());
long importDuration = task.getLastRunFinishTimestamp() - task.getLastRunStartTimestamp();
double usersPerSec = (task.getProgress() * 1000) / importDuration;
display("Imported " + task.getProgress() + " users in " + importDuration + " milliseconds (" + usersPerSec + " users/sec)");
OperationResultStatusType taskResultStatus = task.getResultStatus();
AssertJUnit.assertNotNull("Task has no result status", taskResultStatus);
assertEquals("Import task result is not success", OperationResultStatusType.SUCCESS, taskResultStatus);
AssertJUnit.assertTrue("No progress", task.getProgress() > 0);
//### Check if the import created users and shadows ###
// Listing of shadows is not supported by the provisioning. So we need
// to look directly into repository
List<PrismObject<ShadowType>> sobjects = repositoryService.searchObjects(ShadowType.class, null, null, result);
result.computeStatus();
TestUtil.assertSuccess("listObjects has failed", result);
AssertJUnit.assertFalse("No shadows created", sobjects.isEmpty());
for (PrismObject<ShadowType> aObject : sobjects) {
ShadowType shadow = aObject.asObjectable();
display("Shadow object after import (repo)", shadow);
assertNotEmpty("No OID in shadow", shadow.getOid()); // This would be really strange ;-)
assertNotEmpty("No name in shadow", shadow.getName());
AssertJUnit.assertNotNull("No objectclass in shadow", shadow.getObjectClass());
AssertJUnit.assertNotNull("Null attributes in shadow", shadow.getAttributes());
String resourceOid = shadow.getResourceRef().getOid();
if (resourceOid.equals(RESOURCE_OPENDJ_OID)) {
assertAttributeNotNull("No identifier in shadow", shadow, getOpenDjPrimaryIdentifierQName());
} else {
assertAttributeNotNull("No UID in shadow", shadow, SchemaConstants.ICFS_UID);
}
}
Holder<ObjectListType> listHolder = new Holder<>();
assertNoRepoCache();
modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), null, null,
listHolder, resultHolder);
assertNoRepoCache();
ObjectListType uobjects = listHolder.value;
TestUtil.assertSuccess("listObjects has failed", resultHolder.value);
AssertJUnit.assertFalse("No users created", uobjects.getObject().isEmpty());
// TODO: use another account, not guybrush
display("Users after import "+uobjects.getObject().size());
for (ObjectType oo : uobjects.getObject()) {
UserType user = (UserType) oo;
if (SystemObjectsType.USER_ADMINISTRATOR.value().equals(user.getOid())) {
//skip administrator check
continue;
}
display("User after import (repo)", user);
assertNotEmpty("No OID in user", user.getOid()); // This would be
// really
// strange ;-)
assertNotEmpty("No name in user", user.getName());
assertNotNull("No fullName in user", user.getFullName());
assertNotEmpty("No fullName in user", user.getFullName().getOrig());
assertNotEmpty("No familyName in user", user.getFamilyName().getOrig());
// givenName is not mandatory in LDAP, therefore givenName may not
// be present on user
if (user.getName().getOrig().equals(USER_GUYBRUSH_USERNAME)) {
// skip the rest of checks for guybrush, he does not have LDAP account now
continue;
}
assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null ||
user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED);
List<ObjectReferenceType> accountRefs = user.getLinkRef();
AssertJUnit.assertEquals("Wrong accountRef for user " + user.getName(), 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
boolean found = false;
for (PrismObject<ShadowType> aObject : sobjects) {
ShadowType acc = aObject.asObjectable();
if (accountRef.getOid().equals(acc.getOid())) {
found = true;
break;
}
}
if (!found) {
AssertJUnit.fail("accountRef does not point to existing account " + accountRef.getOid());
}
PrismObject<ShadowType> aObject = modelService.getObject(ShadowType.class, accountRef.getOid(), null, task, result);
ShadowType account = aObject.asObjectable();
display("Account after import ", account);
String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account,
new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "l"));
// assertEquals("Unexcpected value of l", "middle of nowhere", attributeValueL);
assertEquals("Unexcpected value of l", getUserLocality(user), attributeValueL);
}
// This also includes "idm" user imported from LDAP. Later we need to ignore that one.
assertEquals("Wrong number of users after import", 10, uobjects.getObject().size());
checkAllShadows();
}
private String getUserLocality(UserType user){
return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere";
}
@Test
public void test420RecomputeUsers() throws Exception {
final String TEST_NAME = "test420RecomputeUsers";
displayTestTitle(TEST_NAME);
// GIVEN
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Assign role to a user, but we do this using a repository instead of model.
// The role assignment will not be executed and this created an inconsistent state.
ObjectDeltaType changeAddRoleCaptain = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(changeAddRoleCaptain.getItemDelta(),
getUserDefinition());
repositoryService.modifyObject(UserType.class, changeAddRoleCaptain.getOid(), modifications, result);
// TODO: setup more "inconsistent" state
// Add reconciliation task. This will trigger reconciliation
importObjectFromFile(TASK_USER_RECOMPUTE_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task to finish", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, result);
//display("Task while waiting for task manager to pick up the task", task);
// wait until the task is finished
if (TaskExecutionStatus.CLOSED == task.getExecutionStatus()) {
return true;
}
return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 40000);
// wait a second until the task will be definitely saved
Thread.sleep(1000);
// Check task status
Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, retrieveTaskResult(), result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after finish", task);
AssertJUnit.assertNotNull(task.getTaskIdentifier());
assertFalse(task.getTaskIdentifier().isEmpty());
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_USER_RECOMPUTE_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
// .. and last run should not be zero
assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
AssertJUnit.assertEquals(10, task.getProgress());
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
display("Recompute task result", taskResult);
AssertJUnit.assertNotNull(taskResult);
TestUtil.assertSuccess("Recompute task result", taskResult);
// STOP the task. We don't need it any more and we don't want to give it a chance to run more than once
taskManager.deleteTask(TASK_USER_RECOMPUTE_OID, result);
// CHECK RESULT: account created for user guybrush
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> object = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = object.asObjectable();
repoResult.computeStatus();
displayJaxb("User (repository)", repoUser, new QName("user"));
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Wrong number of accountRefs after recompute for user "+repoUser.getName(), 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
checkAllShadows();
}
@Test
public void test440ReconcileResourceOpenDj() throws Exception {
final String TEST_NAME = "test440ReconcileResourceOpenDj";
displayTestTitle(TEST_NAME);
// GIVEN
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Create LDAP account without an owner. The liveSync is off, so it will not be picked up
Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILENAME);
display("Entry from LDIF", ldifEntry);
// Guybrush's attributes were set up by a role in the previous test. Let's mess the up a bit. Recon should sort it out.
List<RawModification> modifications = new ArrayList<>();
// Expect that a correct title will be added to this one
RawModification titleMod = RawModification.create(ModificationType.REPLACE, "title", "Scurvy earthworm");
modifications.add(titleMod);
// Expect that the correct location will replace this one
RawModification lMod = RawModification.create(ModificationType.REPLACE, "l", "Davie Jones' locker");
modifications.add(lMod);
// Expect that this will be untouched
RawModification poMod = RawModification.create(ModificationType.REPLACE, "postOfficeBox", "X marks the spot");
modifications.add(poMod);
ModifyOperation modifyOperation = openDJController.getInternalConnection().processModify(USER_GUYBRUSH_LDAP_DN, modifications);
if (ResultCode.SUCCESS != modifyOperation.getResultCode()) {
AssertJUnit.fail("LDAP operation failed: " + modifyOperation.getErrorMessage());
}
// TODO: setup more "inconsistent" state
// Add reconciliation task. This will trigger reconciliation
repoAddObjectFromFile(TASK_OPENDJ_RECON_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task to finish first run", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result);
display("Task while waiting for task manager to pick up the task", task);
// wait until the task is finished
return task.getLastRunFinishTimestamp() != null;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 180000);
// Check task status
Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after pickup", task);
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_RECON_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and claimed
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
// .. and last run should not be zero
assertNotNull("Null last run start in recon task", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("Zero last run start in recon task", task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull("Null last run finish in recon task", task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("Zero last run finish in recon task", task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be 0, as there were no changes yet
// [pm] commented out, as progress in recon task is now determined not only using # of changes
//AssertJUnit.assertEquals(0, task.getProgress());
// Test for presence of a result. It was not fetched - so it should NOT be there
OperationResult taskResult = task.getResult();
AssertJUnit.assertNull(taskResult);
// However, the task should indicate success
AssertJUnit.assertEquals(OperationResultStatusType.SUCCESS, task.getResultStatus());
// STOP the task. We don't need it any more and we don't want to give it a chance to run more than once
taskManager.deleteTask(TASK_OPENDJ_RECON_OID, result);
// CHECK RESULT: account for user guybrush should be still there and unchanged
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
displayJaxb("User (repository)", repoUser, new QName("user"));
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Guybrush has wrong number of accounts", 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object. It is not tolerant, therefore the other value should be gone now
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
// "title" is tolerant, so it will retain the original value as well as the one provided by the role
OpenDJController.assertAttribute(entry, "title", "Scurvy earthworm", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise");
// No setting for "postOfficeBox", so the value should be unchanged
OpenDJController.assertAttribute(entry, "postOfficeBox", "X marks the spot");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
// QueryType query = QueryUtil.createNameQuery(ELAINE_NAME);
// ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(UserType.class, prismContext, UserType.F_NAME, ELAINE_NAME));
ObjectQuery query = ObjectQueryUtil.createNameQuery(ELAINE_NAME, prismContext);
List<PrismObject<UserType>> users = repositoryService.searchObjects(UserType.class, query, null, repoResult);
assertEquals("Wrong number of Elaines", 1, users.size());
repoUser = users.get(0).asObjectable();
repoResult.computeStatus();
displayJaxb("User Elaine (repository)", repoUser, new QName("user"));
assertNotNull(repoUser.getOid());
assertEquals(PrismTestUtil.createPolyStringType(ELAINE_NAME), repoUser.getName());
PrismAsserts.assertEqualsPolyString("wrong repo givenName", "Elaine", repoUser.getGivenName());
PrismAsserts.assertEqualsPolyString("wrong repo familyName", "Marley", repoUser.getFamilyName());
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Elaine Marley", repoUser.getFullName());
accountRefs = repoUser.getLinkRef();
assertEquals("Elaine has wrong number of accounts", 1, accountRefs.size());
accountRef = accountRefs.get(0);
String accountShadowOidElaineOpendj = accountRef.getOid();
assertFalse(accountShadowOidElaineOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidElaineOpendj,
null, repoResult);
repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
String accountElainehOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account is still in LDAP
entry = openDJController.searchAndAssertByEntryUuid(accountElainehOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", ELAINE_NAME);
OpenDJController.assertAttribute(entry, "givenName", "Elaine");
OpenDJController.assertAttribute(entry, "sn", "Marley");
OpenDJController.assertAttribute(entry, "cn", "Elaine Marley");
OpenDJController.assertAttribute(entry, "displayName", "Elaine Marley");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
// FIXME
//OpenDJController.assertAttribute(entry, "l", "middle of nowhere");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "governor");
OpenDJController.assertAttribute(entry, "title", "Governor");
OpenDJController.assertAttribute(entry, "businessCategory", "state");
String elainePassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Password of Elaine has disappeared", elainePassword);
checkAllShadows();
}
@Test
public void test480ListResources() throws Exception {
final String TEST_NAME = "test480ListResources";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<ObjectListType> objectListHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.searchObjects(ObjectTypes.RESOURCE.getTypeQName(), null, options, objectListHolder, resultHolder);
// THEN
display("Resources", objectListHolder.value);
assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size());
// TODO
for(ObjectType object: objectListHolder.value.getObject()) {
// Marshalling may fail even though the Java object is OK so test for it
String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML);
}
}
@Test
public void test485ListResourcesWithBrokenResource() throws Exception {
TestUtil.displayTestTitle("test485ListResourcesWithBrokenResource");
// GIVEN
Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test410ListResourcesWithBrokenResource");
final OperationResult result = task.getResult();
// WHEN
List<PrismObject<ResourceType>> resources = modelService.searchObjects(ResourceType.class, null, null, task, result);
// THEN
assertNotNull("listObjects returned null list", resources);
for (PrismObject<ResourceType> object : resources) {
ResourceType resource = object.asObjectable();
//display("Resource found",resource);
display("Found " + ObjectTypeUtil.toShortString(resource) + ", result " + (resource.getFetchResult() == null ? "null" : resource.getFetchResult().getStatus()));
assertNotNull(resource.getOid());
assertNotNull(resource.getName());
if (resource.getOid().equals(RESOURCE_BROKEN_OID)) {
assertTrue("No error in fetchResult in " + ObjectTypeUtil.toShortString(resource),
resource.getFetchResult() != null &&
(resource.getFetchResult().getStatus() == OperationResultStatusType.PARTIAL_ERROR ||
resource.getFetchResult().getStatus() == OperationResultStatusType.FATAL_ERROR));
} else {
assertTrue("Unexpected error in fetchResult in " + ObjectTypeUtil.toShortString(resource),
resource.getFetchResult() == null || resource.getFetchResult().getStatus() == OperationResultStatusType.SUCCESS);
}
}
}
@Test
public void test500NotifyChangeCreateAccount() throws Exception{
final String TEST_NAME = "test500NotifyChangeCreateAccount";
displayTestTitle(TEST_NAME);
Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME);
display("Entry from LDIF", ldifEntry);
List<Attribute> attributes = ldifEntry.getAttributes();
List<Attribute> attrs = ldifEntry.getAttribute("entryUUID");
AttributeValue val = null;
if (attrs == null){
for (Attribute a : attributes){
if (a.getName().equals("entryUUID")){
val = a.iterator().next();
}
}
} else{
val = attrs.get(0).iterator().next();
}
String entryUuid = val.toString();
ShadowType anglicaAccount = parseObjectType(new File(ACCOUNT_ANGELIKA_FILENAME), ShadowType.class);
PrismProperty<String> prop = anglicaAccount.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES).getValue().createProperty(
prismContext.definitionFactory().createPropertyDefinition(getOpenDjPrimaryIdentifierQName(), DOMUtil.XSD_STRING));
prop.setRealValue(entryUuid);
anglicaAccount.setResourceRef(ObjectTypeUtil.createObjectRef(RESOURCE_OPENDJ_OID, ObjectTypes.RESOURCE));
display("Angelica shadow: ", anglicaAccount.asPrismObject().debugDump());
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.ADD);
delta.setObjectToAdd(anglicaAccount);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
changeDescription.setObjectDelta(delta);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
PrismObject<ShadowType> modelShadow = modelService.getObject(ShadowType.class, oid, null, taskManager.createTaskInstance(), result);
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(modelShadow, "uid", "angelika");
assertAttribute(modelShadow, "givenName", "Angelika");
assertAttribute(modelShadow, "sn", "Marley");
assertAttribute(modelShadow, "cn", "Angelika Marley");
}
@Test
public void test501NotifyChangeModifyAccount() throws Exception{
final String TEST_NAME = "test501NotifyChangeModifyAccount";
displayTestTitle(TEST_NAME);
OperationResult parentResult = new OperationResult(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.MODIFY);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
ItemDeltaType mod1 = new ItemDeltaType();
mod1.setModificationType(ModificationTypeType.REPLACE);
ItemPathType path = new ItemPathType(ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceTypeOpenDjrepo.getNamespace(), "givenName")));
mod1.setPath(path);
RawType value = new RawType(prismContext.xnodeFactory().primitive("newAngelika"), prismContext);
mod1.getValue().add(value);
delta.getItemDelta().add(mod1);
delta.setOid(oid);
LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1));
LOGGER.info("delta: {}", DebugUtil.dump(mod1));
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
UserType userAfterSync = userAngelikaAfterSync.asObjectable();
PrismAsserts.assertEqualsPolyString("wrong given name in user angelika", PrismTestUtil.createPolyStringType("newAngelika"), userAfterSync.getGivenName());
}
@Test
public void test502NotifyChangeModifyAccountPassword() throws Exception{
final String TEST_NAME = "test502NotifyChangeModifyAccountPassword";
displayTestTitle(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
String newPassword = "newPassword";
openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword);
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.MODIFY);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
ItemDeltaType passwordDelta = new ItemDeltaType();
passwordDelta.setModificationType(ModificationTypeType.REPLACE);
passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext));
RawType passwordValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(ModelClientUtil.createProtectedString(newPassword)).getSubnode(), prismContext);
passwordDelta.getValue().add(passwordValue);
delta.getItemDelta().add(passwordDelta);
delta.setOid(oid);
LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta));
LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta));
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
// changeDescription.setCurrentShadow(angelicaShadowType);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
assertUserLdapPassword(userAngelikaAfterSync, newPassword);
}
@Test
public void test503NotifyChangeDeleteAccount() throws Exception{
final String TEST_NAME = "test503NotifyChangeDeleteAccount";
displayTestTitle(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.DELETE);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
delta.setOid(oid);
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertTrue(result.isAcceptable());
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
display("User after", userAngelikaAfterSync);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
UserType userType = userAngelikaAfterSync.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", userType.getLinkRef());
assertEquals("Expected no account ref in user", 0, userType.getLinkRef().size());
}
@Test
public void test999Shutdown() throws Exception {
taskManager.shutdown();
waitFor("waiting for task manager shutdown", new Checker() {
@Override
public boolean check() {
return taskManager.getLocallyRunningTasks(new OperationResult("dummy")).isEmpty();
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 10000);
AssertJUnit.assertEquals("Some tasks left running after shutdown", new HashSet<Task>(),
new HashSet<>(taskManager.getLocallyRunningTasks(new OperationResult("dummy"))));
}
// TODO: test for missing/corrupt system configuration
// TODO: test for missing sample config (bad reference in expression
// arguments)
private String checkRepoShadow(PrismObject<ShadowType> repoShadow) {
ShadowType repoShadowType = repoShadow.asObjectable();
String uid = null;
boolean hasOthers = false;
List<Object> xmlAttributes = repoShadowType.getAttributes().getAny();
for (Object element : xmlAttributes) {
if (SchemaConstants.ICFS_UID.equals(JAXBUtil.getElementQName(element)) || getOpenDjPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) {
if (uid != null) {
AssertJUnit.fail("Multiple values for ICF UID in shadow attributes");
} else {
uid = ((Element) element).getTextContent();
}
} else if (SchemaConstants.ICFS_NAME.equals(JAXBUtil.getElementQName(element)) || getOpenDjSecondaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) {
// This is OK
} else {
hasOthers = true;
}
}
assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers);
assertNotNull(uid);
return uid;
}
private QName getOpenDjPrimaryIdentifierQName() {
return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME);
}
private QName getOpenDjSecondaryIdentifierQName() {
return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME);
}
private ShadowType searchAccountByOid(final String accountOid) throws Exception {
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<ObjectType> accountHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountOid, options, accountHolder, resultHolder);
ObjectType object = accountHolder.value;
TestUtil.assertSuccess("searchObjects has failed", resultHolder.value);
assertNotNull("Account is null", object);
if (!(object instanceof ShadowType)) {
fail("Object is not account.");
}
ShadowType account = (ShadowType) object;
assertEquals(accountOid, account.getOid());
return account;
}
private UserType searchUserByName(String name) throws Exception {
// Document doc = DOMUtil.getDocument();
// Element nameElement = doc.createElementNS(SchemaConstants.C_NAME.getNamespaceURI(),
// SchemaConstants.C_NAME.getLocalPart());
// nameElement.setTextContent(name);
// Element filter = QueryUtil.createEqualFilter(doc, null, nameElement);
//
// QueryType query = new QueryType();
// query.setFilter(filter);
ObjectQuery q = ObjectQueryUtil.createNameQuery(UserType.class, prismContext, name);
QueryType query = prismContext.getQueryConverter().createQueryType(q);
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<ObjectListType> listHolder = new Holder<>();
assertNoRepoCache();
modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), query, null, listHolder, resultHolder);
assertNoRepoCache();
ObjectListType objects = listHolder.value;
TestUtil.assertSuccess("searchObjects has failed", resultHolder.value);
AssertJUnit.assertEquals("User not found (or found too many)", 1, objects.getObject().size());
UserType user = (UserType) objects.getObject().get(0);
AssertJUnit.assertEquals(user.getName(), PrismTestUtil.createPolyStringType(name));
return user;
}
private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, int increment,
final OperationResult result) throws Exception {
basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result);
}
private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment,
final OperationResult result) throws Exception {
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, increment, result, 40000);
}
private void basicWaitForSyncChangeDetection(final Task syncCycle, final int tokenBefore, final int increment,
final OperationResult result, int timeout) throws Exception {
waitFor("Waiting for sync cycle to detect change", new Checker() {
@Override
public boolean check() throws CommonException {
syncCycle.refresh(result);
display("SyncCycle while waiting for sync cycle to detect change", syncCycle);
if (syncCycle.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) {
throw new IllegalStateException("Task not runnable: "+syncCycle.getExecutionStatus()+"; "+syncCycle);
}
int tokenNow = findSyncToken(syncCycle);
display("tokenNow = " + tokenNow);
if (tokenNow >= tokenBefore + increment) {
return true;
} else {
return false;
}
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, timeout, WAIT_FOR_LOOP_SLEEP_MILIS);
}
private void setAssignmentEnforcement(AssignmentPolicyEnforcementType enforcementType) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
assumeAssignmentPolicy(enforcementType);
// AccountSynchronizationSettingsType syncSettings = new AccountSynchronizationSettingsType();
// syncSettings.setAssignmentPolicyEnforcement(enforcementType);
// applySyncSettings(SystemConfigurationType.class, syncSettings);
}
private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType assignmentPolicy) throws
ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult("Asserting sync settings");
PrismObject<SystemConfigurationType> systemConfigurationType = repositoryService.getObject(SystemConfigurationType.class,
SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result);
result.computeStatus();
TestUtil.assertSuccess("Asserting sync settings failed (result)", result);
ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.asObjectable().getGlobalAccountSynchronizationSettings();
assertNotNull("globalAccountSynchronizationSettings is null", globalAccountSynchronizationSettings);
AssignmentPolicyEnforcementType assignmentPolicyEnforcement = globalAccountSynchronizationSettings.getAssignmentPolicyEnforcement();
assertNotNull("assignmentPolicyEnforcement is null", assignmentPolicyEnforcement);
assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement);
}
private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException {
LOGGER.trace("Checking all shadows");
System.out.println("Checking all shadows");
ObjectChecker<ShadowType> checker = null;
IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext);
}
public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedObjectClassDefinition objClassDef, QName name) {
String value = getAttributeValue(repoShadow, name);
RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next();
if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)){
return value.toLowerCase();
}
return value;
}
protected <T> void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) {
assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues);
}
protected <T> void assertAttribute(PrismObject<ShadowType> shadow, String attrName, T... expectedValues) {
assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues);
}
}
|
Java
|
/*
* Copyright 2017 Crown Copyright
*
* 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 stroom.security.identity.authenticate;
import stroom.security.identity.authenticate.api.AuthenticationService;
import stroom.util.guice.RestResourcesBinder;
import com.google.inject.AbstractModule;
public final class AuthenticateModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthenticationService.class).to(AuthenticationServiceImpl.class);
RestResourcesBinder.create(binder())
.bind(AuthenticationResourceImpl.class);
}
}
|
Java
|
<?php
namespace DCarbone\PHPFHIRGenerated\STU3\FHIRElement;
/*!
* This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using
* class definitions from HL7 FHIR (https://www.hl7.org/fhir/)
*
* Class creation date: December 26th, 2019 15:43+0000
*
* PHPFHIR Copyright:
*
* Copyright 2016-2019 Daniel Carbone (daniel.p.carbone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* FHIR Copyright Notice:
*
* Copyright (c) 2011+, HL7, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of HL7 nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1
*
* Note: the schemas & schematrons do not contain all of the rules about what makes resources
* valid. Implementers will still need to be familiar with the content of the specification and with
* any profiles that apply to the resources in order to make a conformant implementation.
*
*/
use DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTypeInterface;
/**
* Different measurement principle supported by the device.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Class FHIRMeasmntPrinciple
* @package \DCarbone\PHPFHIRGenerated\STU3\FHIRElement
*/
class FHIRMeasmntPrinciple extends FHIRElement
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE;
const FIELD_VALUE = 'value';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList
*/
protected $value = null;
/**
* Validation map for fields in type MeasmntPrinciple
* @var array
*/
private static $_validationRules = [ ];
/**
* FHIRMeasmntPrinciple Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (is_scalar($data)) {
$this->setValue(new FHIRMeasmntPrincipleList($data));
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIRMeasmntPrinciple::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_VALUE])) {
$this->setValue($data[self::FIELD_VALUE]);
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<MeasmntPrinciple{$xmlns}></MeasmntPrinciple>";
}
/**
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList
*/
public function getValue()
{
return $this->value;
}
/**
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList $value
* @return static
*/
public function setValue($value = null)
{
if (null === $value) {
$this->value = null;
return $this;
}
if ($value instanceof FHIRMeasmntPrincipleList) {
$this->value = $value;
return $this;
}
$this->value = new FHIRMeasmntPrincipleList($value);
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if (null !== ($v = $this->getValue())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_VALUE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_VALUE])) {
$v = $this->getValue();
foreach($validationRules[self::FIELD_VALUE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE, self::FIELD_VALUE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_VALUE])) {
$errs[self::FIELD_VALUE] = [];
}
$errs[self::FIELD_VALUE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_EXTENSION])) {
$v = $this->getExtension();
foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_EXTENSION])) {
$errs[self::FIELD_EXTENSION] = [];
}
$errs[self::FIELD_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIRMeasmntPrinciple;
} elseif (!is_object($type) || !($type instanceof FHIRMeasmntPrinciple)) {
throw new \RuntimeException(sprintf(
'FHIRMeasmntPrinciple::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRElement::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->value)) {
$type->setValue(FHIRMeasmntPrincipleList::xmlUnserialize($children->value));
}
if (isset($attributes->value)) {
$pt = $type->getValue();
if (null !== $pt) {
$pt->setValue((string)$attributes->value);
} else {
$type->setValue((string)$attributes->value);
}
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if (null !== ($v = $this->getValue())) {
$sxe->addAttribute(self::FIELD_VALUE, (string)$v);
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if (null !== ($v = $this->getValue())) {
$a[self::FIELD_VALUE] = $v;
}
return $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
}
|
Java
|
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive;
using Xamarin.Forms;
using RxObservable = System.Reactive.Linq.Observable;
using System.Reactive.Linq;
namespace RxApp.XamarinForms
{
public static class Bindings
{
public static IDisposable BindTo(
this IObservable<NavigationStack> This,
RxFormsApplication application,
Func<INavigationViewModel,Page> createPage)
{
var navigationPage = application.MainPage;
var popping = false;
var stack = This
.ObserveOnMainThread()
.Scan(Tuple.Create(RxApp.NavigationStack.Empty, RxApp.NavigationStack.Empty), (acc, navStack) => Tuple.Create(acc.Item2, navStack))
.SelectMany(async x =>
{
var previousNavStack = x.Item1;
var currentNavStack = x.Item2;
var currentPage = (navigationPage.CurrentPage as IReadOnlyViewFor);
var navPageModel = (currentPage != null) ? (currentPage.ViewModel as INavigationViewModel) : null;
var head = currentNavStack.FirstOrDefault();
if (currentNavStack.IsEmpty)
{
// Do nothing. Can only happen on Android. Android handles the stack being empty by
// killing the activity.
}
else if (head == navPageModel)
{
// Do nothing, means the user clicked the back button which we cant intercept,
// so we let forms pop the view, listen for the popping event, and then popped the view model.
}
else if (currentNavStack.Pop().Equals(previousNavStack))
{
var view = createPage(head);
await navigationPage.PushAsync(view, true);
}
else if (previousNavStack.Pop().Equals(currentNavStack))
{
// Programmatic back button was clicked
popping = true;
await navigationPage.PopAsync(true);
popping = false;
}
else if (previousNavStack.Up().Equals(currentNavStack))
{
// Programmatic up button was clicked
popping = true;
await navigationPage.PopToRootAsync(true);
popping = false;
}
return currentNavStack;
})
.Publish();
return Disposable.Compose(
stack.Where(x => x.IsEmpty).Subscribe(_ => application.SendDone()),
// Handle the user clicking the back button
RxObservable.FromEventPattern<NavigationEventArgs>(navigationPage, "Popped")
.Where(_ => !popping)
.Subscribe(e =>
{
var vm = ((e.EventArgs.Page as IReadOnlyViewFor).ViewModel as INavigationViewModel);
vm.Activate.Execute();
vm.Back.Execute();
vm.Deactivate.Execute();
}),
stack.Connect()
);
}
public static IDisposable BindTo<T, TView>(this IObservable<T> This, TView target, Expression<Func<TView, T>> property)
{
return This.BindTo(target, property, Scheduler.MainThreadScheduler);
}
public static IDisposable BindTo(this IObservable<Unit> This, Action action)
{
return This.ObserveOnMainThread().Subscribe(_ => action());
}
public static IDisposable BindTo<T>(this IObservable<T> This, Action<T> action)
{
return This.ObserveOnMainThread().Subscribe(action);
}
public static IDisposable Bind(this IRxCommand This, Button button)
{
return Disposable.Compose(
This.CanExecute.ObserveOnMainThread().Subscribe(x => button.IsEnabled = x),
RxObservable.FromEventPattern(button, "Clicked").InvokeCommand(This)
);
}
}
}
|
Java
|
/*
* Copyright (c) 2012-2015 S-Core 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.
*/
require([
'common',
'lodash',
'moment',
'async',
'text!resource/add_wsdlg.html',
'text!resource/remove_wsdlg.html'
], function (common, _, moment, async, addDlg, removeDlg) {
'use strict';
/* global webidaFs, webidaApp, webidaAuth, webidaHost: true */
var WORKSPACE_PATH = '.profile/workspace.json';
var WORKSPACE_INFO;
//var _menuSettings = $('#menu-settings');
var _wsContents = $('.ws-body');
var _dimming = $('.dimming');
var _uniqId;
function _dimmingOn() {
_dimming.addClass('active');
}
function _dimmingOff() {
_dimming.removeClass('active');
}
function _checkValidWSFile(cb) {
webidaFs.readFile(WORKSPACE_PATH, function (err, data) {
if (err) {
cb('_checkValidWSFile() - readFile Error: ' + err);
} else {
var wsMeta = JSON.parse(data);
var wsMetaCount = Object.keys(wsMeta).length;
_getWSList(function (err, wslist) {
if (err) {
cb('_checkValidWSFile() - _getWSList Error: ' + err);
} else {
var wsCount = wslist.length;
if (wsMetaCount === wsCount) {
cb(null, true);
} else {
cb(null, false);
}
}
});
}
});
}
function _launchIDE(domObj) {
console.log($(domObj).attr('data-wsname'));
var workspace = '?workspace=' + webidaFs.fsid + '/' + domObj.attr('data-wsname');
webidaApp.launchApp('devenv', true, workspace);
}
function _registerDefaultEvent() {
// register dimming cancel event
_dimming.on('click', function () {
_dimming.removeClass('active');
var addWSDlg = $('.add_wsdlg');
var removeWSDlg = $('.remove_wsdlg');
if (addWSDlg) {
addWSDlg.remove();
}
if (removeWSDlg) {
removeWSDlg.remove();
}
});
$('#menu-logo').on('click', function () {
webidaApp.launchApp('desktop', false, null);
});
// register workspace event
$('#menu-ws').on('click', function () {
var wswrap = $('.ws-wrap');
var settingwrap = $('.settings-wrap');
if (wswrap.hasClass('acitve')) {
settingwrap.removeClass('active');
} else {
wswrap.addClass('active');
settingwrap.removeClass('active');
}
});
// register setting event
$('#menu-settings').on('click', function () {
var wswrap = $('.ws-wrap');
var settingwrap = $('.settings-wrap');
if (settingwrap.hasClass('acitve')) {
wswrap.removeClass('active');
} else {
settingwrap.addClass('active');
wswrap.removeClass('active');
}
});
// register logout event
$('#menu-logout').on('click', function () {
_setLogout();
});
// register workspace add event
$('.ws-icon-add').on('click', function () {
_addWSList();
});
}
// WORKSPACE_PATH 파일이 있는지 없는지 여부 확인 후 없으면 생성.
function _initialize() {
_registerDefaultEvent();
webidaFs.exists(WORKSPACE_PATH, function (err, exist) {
if (err) {
console.log('_checkWSFile() - exists Error: ' + err);
}
if (!exist) {
_setWorkspace(function (err) {
if (err) {
console.log(err);
}
_renderWSList();
});
} else {
_checkValidWSFile(function (err, bool) {
if (err) {
console.log(err);
} else {
if (bool) {
_renderWSList();
} else {
console.log('workspace meta-info is invalid.');
_renderWSList();
}
}
});
}
});
}
// WORKSPACE 목록 생성 및 WORKSPACE_PATH에 정보 저장.
function _setWorkspace(cb) {
webidaFs.list('/', function (err, data) {
if (err) {
console.log('setWorkspace() - list Error: ' + err);
cb(err);
} else {
var WSList =
_.chain(data).filter(function (fileObj) {
if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; }
}).map(function (fileObj) { return '/' + fileObj.name; }).value();
webidaFs.stat(WSList, function (err, stats) {
if (err) {
console.log('setWorkspace() - stat Error: ' + err);
cb(err);
} else {
var wsObj = {};
_.forEach(stats, function (fileObj) {
fileObj.birth = '';
fileObj.desc = '';
wsObj[fileObj.name] = fileObj;
});
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(wsObj), function (err) {
if (err) {
console.log('setWorkspace() - writeFile Error: ' + err);
cb(err);
} else {
cb(null, true);
}
});
}
});
}
});
}
// 유니크 id 생성.
function _genUniuqeId() {
_uniqId = _.uniqueId();
return _uniqId;
}
// 로그아웃
function _setLogout() {
webidaAuth.logout(function (err) {
if (err) {
alert('Failed to logout');
} else {
location.href = '//' + webidaHost;
}
});
}
function _getWSList(cb) {
webidaFs.list('/', function (err, data) {
if (err) {
cb(err);
} else {
var WSList =
_.chain(data).filter(function (fileObj) {
if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; }
}).map(function (fileObj) { return '/' + fileObj.name; }).value();
webidaFs.stat(WSList, function (err, stats) {
if (err) {
cb(err);
} else {
cb(null, stats);
}
});
}
});
}
// 프로젝트 목록 얻어오기
function _getPJListPath(WSPath, cb) {
webidaFs.list(WSPath, function (err, pjList) {
if (err) {
cb(err);
} else {
var filteredPJList =
_.chain(pjList).filter(function (file) {
if (!file.name.match('.workspace') && file.isDirectory) {
return true;
}
}).map(function (file) {
return WSPath + '/' + file.name + '/.project/project.json';
}).value();
return cb(null, filteredPJList);
}
});
}
// 프로젝트 목록 그리기
function _renderPJList(domObj) {
var ws = domObj.attr('data-wspath');
var wsRow = domObj.parent();
if (wsRow.hasClass('ws-closed')) {
wsRow.addClass('ws-opened');
wsRow.removeClass('ws-closed');
wsRow.after('<div class="pj-body" data-id="' + wsRow.attr('data-id') + '"></div>');
var proRow = wsRow.next();
_getPJListPath(ws, function (err, pjPathList) {
if (err) {
console.log('_renderPJList() - _getPJListPath Error: ' + err);
} else {
_.forEach(pjPathList, function (pjPath) {
webidaFs.exists(pjPath, function (err, exist) {
if (err) {
console.log('_renderPJList() - exists Error: ' + err);
}
if (exist) {
webidaFs.readFile(pjPath, function (err, data) {
if (err) {
console.log('_renderPJList() - read Error: ' + err);
} else {
var projInfo = JSON.parse(data);
/* jshint maxlen : 200 */
var template =
'<div class="pj-row"">' +
'<div class="pj-content">' +
'<div class="pj-item pj-arrow"></div>' +
'<div class="pj-item pj-name">' + projInfo.name + '</div>' +
'<div class="pj-item pj-ltime"></div>' +
'<div class="pj-item pj-birth">' + moment(projInfo.created).fromNow() + '</div>' +
'<div class="pj-item pj-desc">' + projInfo.description + '</div>' +
'</div>' +
'<div class="pj-content-icon">' +
'</div>' +
'</div>';
/* jshint maxlen:120 */
proRow.append(template);
}
});
}
});
});
}
});
} else {
var projRow = wsRow.next();
if (projRow.hasClass('pj-body') && (projRow.attr('data-id') === wsRow.attr('data-id'))) {
projRow.remove();
wsRow.removeClass('ws-opened');
wsRow.addClass('ws-closed');
}
}
}
// 워크스페이스 목록 그리기
function _renderWSList() {
if (_wsContents.children.length) {
_wsContents.empty();
}
webidaFs.readFile(WORKSPACE_PATH, function (err, data) {
if (err) {
console.log('_renderWSList() - readFile Error: ' + err);
} else {
var wsObj = JSON.parse(data);
WORKSPACE_INFO = wsObj;
_.forEach(wsObj, function (ws) {
var id = _genUniuqeId();
var birth = '';
var desc = '';
if (ws.birth) {
birth = moment(ws.birth).fromNow();
}
if (ws.desc) {
desc = ws.desc;
}
/* jshint maxlen : 200 */
var template =
'<div class="ws-row ws-closed" data-id="' + id + '">' +
'<div class="ws-content" data-wspath="' + ws.path + '">' +
'<div class="ws-item ws-arrow"></div>' +
'<div class="ws-item ws-name">' + ws.name + '</div>' +
'<div class="ws-item ws-ltime">' + moment(ws.mtime).fromNow() + '</div>' +
'<div class="ws-item ws-birth">' + birth + '</div>' +
'<div class="ws-item ws-desc">' + desc + '</div>' +
'</div>' +
'<div class="ws-content-icon">' +
'<div class="ws-launch">' +
'<div class="ws-icon-launch" title="Launch IDE" data-wsname="' + ws.name + '"></div>' +
'</div>' +
'<div class="ws-delete">' +
'<div class="ws-icon-delete" title="Delete Workspace" data-wsname="' + ws.name + '" data-id="' + id + '"></div>' +
'</div>' +
'</div>' +
'</div>';
/* jshint maxlen : 120 */
_wsContents.append(template);
});
// register get project event
$('.ws-body .ws-content').on('click', function (evt) {
var domObj = $(evt.target).parent();
_renderPJList(domObj);
});
// register launch event
$('.ws-icon-launch').on('click', function (evt) {
var domObj = $(evt.target);
_launchIDE(domObj);
});
$('.ws-icon-delete').on('click', function (evt) {
var domObj = $(evt.target);
_removeWSList(domObj);
});
}
});
}
function _addWSList() {
_dimmingOn();
$('body').append(addDlg);
// register dialog close event
$('.adddlg_close').on('click', function () {
$('.add_wsdlg').remove();
_dimmingOff();
});
// input에 포커스
$('#workspace_name').focus();
$('#workspace_name').on('keyup', function () {
var wsname = this.value;
if (wsname) {
$('#adddlg_message').text('');
}
});
// register create workspace event
$('#adddlg_confirm').on('click', function (evt) {
evt.preventDefault();
var wsname = $('#workspace_name').val();
var wsdesc = $('#workspace_desc').val();
var message = $('#adddlg_message');
if (!wsname) {
message.text('Please enter workspace name.');
return;
}
_getWSList(function (err, wslist) {
if (err) {
console.log('_addWSList()' + err);
} else {
var isExist = _.find(wslist, { 'name' : wsname });
if (isExist) {
message.text('\'' + wsname + '\' worskpace is already existed.');
return;
} else {
// create workspace
var WS_META_PATH = wsname + '/.workspace';
var WS_META_FILE = WS_META_PATH + '/workspace.json';
async.waterfall([
function (next) {
webidaFs.createDirectory(wsname, false, function (err) {
if (err) {
next('_addWSList() - 1st createDirectory Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.createDirectory(WS_META_PATH, false, function (err) {
if (err) {
next('_addWSList() - 2nd createDirectory Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.writeFile(WS_META_FILE, '', function (err) {
if (err) {
next('_addWSList() - 1st writeFile Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.stat([wsname], function (err, stats) {
if (err) {
next('_addWSList() - stat Error:' + err);
} else {
stats[0].birth = new Date().toJSON();
stats[0].desc = wsdesc;
WORKSPACE_INFO[wsname] = stats[0];
next();
}
});
},
function (next) {
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) {
if (err) {
next('_addWSList() - 2nd writeFile Error:' + err);
} else {
next();
}
});
}
], function (err) {
if (err) {
console.log(err);
} else {
$('.add_wsdlg').remove();
_dimmingOff();
_renderWSList();
}
});
}
}
});
});
}
function _removeWSList(domObj) {
_dimmingOn();
$('body').append(removeDlg);
$('.removedlg_close').on('click', function () {
$('.remove_wsdlg').remove();
_dimmingOff();
});
var deleteWSname = domObj.attr('data-wsname');
var msg = '<p>This action <strong style="color:#fff">CANNOT</strong> be undone. ' +
'This will delete the <span style="color:#fff; font-weight:bold;">' +
deleteWSname + '</span> workspace and projects permanetly.</p>' +
'<p>Please type in the name of the workspace to confirm.</p>';
$('.removedlg_warning_text').html(msg);
// input에 포커스
$('#workspace_name').focus();
$('#workspace_name').on('keyup', function () {
var wsname = this.value;
if (wsname) {
$('#removedlg_message').text('');
}
});
$('#removedlg_confirm').on('click', function (evt) {
evt.preventDefault();
var wsname = $('#workspace_name').val();
var message = $('#removedlg_message');
if (!wsname) {
message.text('Please enter workspace name.');
return;
} else if (wsname !== deleteWSname) {
message.text('workspace name doesn\'t match.');
return;
}
if (WORKSPACE_INFO[deleteWSname]) {
delete WORKSPACE_INFO[deleteWSname];
async.waterfall([
function (next) {
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) {
if (err) {
err('_removeWSList() - writeFile Error: ' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.delete(deleteWSname, true, function (err) {
if (err) {
next('_removeWSList() - delete Error:' + err);
} else {
next();
}
});
}
], function (err) {
if (err) {
console.log(err);
} else {
var id = domObj.attr('data-id');
var selectorWS = '.ws-row[data-id=' + id + ']';
var selectorProj = '.pj-body[data-id=' + id + ']';
$(selectorWS).remove();
if ($(selectorProj)) {
$(selectorProj).remove();
}
$('.remove_wsdlg').remove();
_dimmingOff();
}
});
}
});
}
common.getFS(function (exist) {
if (exist) {
_initialize();
} else {
location.href = '//' + webidaHost;
}
});
});
|
Java
|
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `KBOOpenData_activity`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_activity`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_activity` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`ActivityGroup` varchar(6) NOT NULL COMMENT '(6)X',
`NaceVersion` enum('2003','2008') NOT NULL,
`NaceCode` varchar(9) NOT NULL COMMENT '(5)9 of (7)9',
`Classification` char(4) NOT NULL COMMENT 'XXXX',
PRIMARY KEY (`EntityNumber`,`ActivityGroup`,`NaceVersion`,`NaceCode`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_address`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_address`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_address` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`TypeOfAddress` char(4) NOT NULL COMMENT 'XXXX',
`CountryNL` varchar(100) DEFAULT NULL COMMENT '100(X)',
`CountryFR` varchar(100) DEFAULT NULL COMMENT '100(X)',
`Zipcode` varchar(20) DEFAULT NULL COMMENT '20(X)',
`MunicipalityNL` varchar(200) DEFAULT NULL COMMENT '200(X)',
`MunicipalityFR` varchar(200) DEFAULT NULL COMMENT '200(X)',
`StreetNL` varchar(200) DEFAULT NULL COMMENT '200(X)',
`StreetFR` varchar(200) DEFAULT NULL COMMENT '200(X)',
`HouseNumber` varchar(22) DEFAULT NULL COMMENT '22(X)',
`Box` varchar(20) DEFAULT NULL COMMENT '20(X)',
`ExtraAddressInfo` varchar(80) DEFAULT NULL COMMENT '80(X)',
`DateStrikingOff` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
PRIMARY KEY (`EntityNumber`,`TypeOfAddress`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_code`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_code`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_code` (
`Category` varchar(255) NOT NULL,
`Code` varchar(255) NOT NULL,
`Language` enum('DE','EN','FR','NL') NOT NULL,
`Description` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_contact`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_contact`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_contact` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`EntityContact` varchar(3) NOT NULL COMMENT '(3)X',
`ContactType` varchar(5) NOT NULL COMMENT '5(X)',
`Value` varchar(254) NOT NULL COMMENT '(254)X',
PRIMARY KEY (`EntityNumber`,`EntityContact`,`ContactType`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_denomination`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_denomination`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_denomination` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`Language` char(1) NOT NULL COMMENT 'X',
`TypeOfDenomination` char(3) NOT NULL COMMENT 'XXX',
`Denomination` varchar(320) NOT NULL COMMENT '(320)X',
PRIMARY KEY (`EntityNumber`,`TypeOfDenomination`,`Language`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_enterprise`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_enterprise`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_enterprise` (
`EnterpriseNumber` varchar(12) NOT NULL COMMENT '9999.999.999',
`Status` char(2) NOT NULL COMMENT 'XX',
`JuridicalSituation` char(3) NOT NULL COMMENT 'XXX',
`TypeOfEnterprise` char(1) NOT NULL COMMENT 'X',
`JuridicalForm` char(3) DEFAULT NULL COMMENT 'XXX',
`StartDate` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
PRIMARY KEY (`EnterpriseNumber`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_establishment`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_establishment`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_establishment` (
`EstablishmentNumber` varchar(13) NOT NULL DEFAULT '' COMMENT '9.999.999.999',
`StartDate` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
`EnterpriseNumber` varchar(12) NOT NULL COMMENT '9999.999.999',
PRIMARY KEY (`EstablishmentNumber`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_meta`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_meta`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_meta` (
`Variable` varchar(255) NOT NULL,
`Value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Variable`),
UNIQUE KEY `metaUnique` (`Variable`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_mutationlog`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_mutationlog`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_mutationlog` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`tableName` varchar(64) NOT NULL,
`recordKey` varchar(32) NOT NULL,
`data_old` text,
`data_new` text,
`action` enum('insert','update','delete') NOT NULL,
`mutationTimestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=ARCHIVE AUTO_INCREMENT=64756 DEFAULT CHARSET=utf8;
|
Java
|
package com.example.android.bluetoothlegatt.ble_service;
/**
* @author Sopheak Tuon
* @created on 04-Oct-17
*/
import java.util.Locale;
public class CountryUtils {
public static boolean getMonthAndDayFormate() {
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
String contr = locale.getCountry();
if (lang == null || (!lang.equals("zh") && !lang.equals("ja") && !lang.equals("ko") && (!lang.equals("en") || contr == null || !contr.equals("US")))) {
return false;
}
return true;
}
public static boolean getLanguageFormate() {
String language = Locale.getDefault().getLanguage();
if (language == null || !language.equals("zh")) {
return false;
}
return true;
}
}
|
Java
|
# coding=utf8
from django.views.generic import ListView, DetailView, CreateView
from django.db.models import Q
from django.http import JsonResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from pure_pagination.mixins import PaginationMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from books.models import Publish, Author, Book
from books.forms import PublishForm
import json
import logging
logger = logging.getLogger('opsweb')
class PublishListView(LoginRequiredMixin, PaginationMixin, ListView):
'''
动作:getlist, create
'''
model = Publish
template_name = "books/publish_list.html"
context_object_name = "publish_list"
paginate_by = 5
keyword = ''
def get_queryset(self):
queryset = super(PublishListView, self).get_queryset()
self.keyword = self.request.GET.get('keyword', '').strip()
if self.keyword:
queryset = queryset.filter(Q(name__icontains=self.keyword) |
Q(address__icontains=self.keyword) |
Q(city__icontains=self.keyword))
return queryset
def get_context_data(self, **kwargs):
context = super(PublishListView, self).get_context_data(**kwargs)
context['keyword'] = self.keyword
return context
def post(self, request):
form = PublishForm(request.POST)
if form.is_valid():
form.save()
res = {'code': 0, 'result': '添加出版商成功'}
else:
# form.errors会把验证不通过的信息以对象的形式传到前端,前端直接渲染即可
res = {'code': 1, 'errmsg': form.errors}
print form.errors
return JsonResponse(res, safe=True)
class PublishDetailView(LoginRequiredMixin, DetailView):
'''
动作:getone, update, delete
'''
model = Publish
template_name = "books/publish_detail.html"
context_object_name = 'publish'
next_url = '/books/publishlist/'
def post(self, request, *args, **kwargs):
pk = kwargs.get('pk')
p = self.model.objects.get(pk=pk)
form = PublishForm(request.POST, instance=p)
if form.is_valid():
form.save()
res = {"code": 0, "result": "更新出版商成功", 'next_url': self.next_url}
else:
res = {"code": 1, "errmsg": form.errors, 'next_url': self.next_url}
return render(request, settings.JUMP_PAGE, res)
# return HttpResponseRedirect(reverse('books:publish_detail',args=[pk]))
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
# 通过出版社对象查所在该出版社的书籍,如果有关联书籍不可以删除,没有关联书籍可以删除
try:
obj = self.model.objects.get(pk=pk)
if not obj.book_set.all():
self.model.objects.filter(pk=pk).delete()
res = {"code": 0, "result": "删除出版商成功"}
else:
res = {"code": 1, "errmsg": "该出版社有关联书籍,请联系管理员"}
except:
res = {"code": 1, "errmsg": "删除错误请联系管理员"}
return JsonResponse(res, safe=True)
|
Java
|
/*
* 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.workmailmessageflow.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.workmailmessageflow.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* MessageRejectedException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MessageRejectedExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private MessageRejectedExceptionUnmarshaller() {
super(com.amazonaws.services.workmailmessageflow.model.MessageRejectedException.class, "MessageRejected");
}
@Override
public com.amazonaws.services.workmailmessageflow.model.MessageRejectedException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {
com.amazonaws.services.workmailmessageflow.model.MessageRejectedException messageRejectedException = new com.amazonaws.services.workmailmessageflow.model.MessageRejectedException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return messageRejectedException;
}
private static MessageRejectedExceptionUnmarshaller instance;
public static MessageRejectedExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new MessageRejectedExceptionUnmarshaller();
return instance;
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sat May 16 22:22:30 CEST 2015 -->
<title>StreamMessage.Type</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="StreamMessage.Type";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/streaming/messages/StreamMessage.Type.html" target="_top">Frames</a></li>
<li><a href="StreamMessage.Type.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.streaming.messages</div>
<h2 title="Enum StreamMessage.Type" class="title">Enum StreamMessage.Type</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.streaming.messages.StreamMessage.Type</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">StreamMessage.Type</span>
extends java.lang.Enum<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></pre>
<div class="block">StreamMessage types</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#COMPLETE">COMPLETE</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#FILE">FILE</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#PREPARE">PREPARE</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#RECEIVED">RECEIVED</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#RETRY">RETRY</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#SESSION_FAILED">SESSION_FAILED</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#inSerializer">inSerializer</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#outSerializer">outSerializer</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#priority">priority</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#get(byte)">get</a></strong>(byte type)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="PREPARE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PREPARE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> PREPARE</pre>
</li>
</ul>
<a name="FILE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>FILE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> FILE</pre>
</li>
</ul>
<a name="RECEIVED">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RECEIVED</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> RECEIVED</pre>
</li>
</ul>
<a name="RETRY">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RETRY</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> RETRY</pre>
</li>
</ul>
<a name="COMPLETE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>COMPLETE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> COMPLETE</pre>
</li>
</ul>
<a name="SESSION_FAILED">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SESSION_FAILED</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> SESSION_FAILED</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="priority">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>priority</h4>
<pre>public final int priority</pre>
</li>
</ul>
<a name="inSerializer">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inSerializer</h4>
<pre>public final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>> inSerializer</pre>
</li>
</ul>
<a name="outSerializer">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>outSerializer</h4>
<pre>public final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>> outSerializer</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (StreamMessage.Type c : StreamMessage.Type.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
<a name="get(byte)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> get(byte type)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/streaming/messages/StreamMessage.Type.html" target="_top">Frames</a></li>
<li><a href="StreamMessage.Type.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
"use strict";
var router_1 = require('@angular/router');
var authorize_component_1 = require('./authorize/authorize-component');
var user_component_1 = require('./User/user-component');
var welcome_component_1 = require('./welcome-component');
exports.routes = [
{ path: '', component: welcome_component_1.welcome },
{ path: 'login', component: authorize_component_1.AuthorizeComponent },
{ path: 'dashboard', component: user_component_1.UserComponent },
];
exports.APP_ROUTER_PROVIDERS = [
router_1.provideRouter(exports.routes)
];
//# sourceMappingURL=app.route.js.map
|
Java
|
<?php
namespace Home\Controller;
class EmptyController extends HomeController{
public function _empty($action){
$resource = strtolower(CONTROLLER_NAME);
$this->assign('type', $resource);
if(in_array($resource, array('text', 'picture', 'music', 'video'))){
if(in_array($action, array('new', 'edit'))){
if('edit' == $action){
$id = intval(I('id'));
if($post = M('post')->find($id))
$this->assign('post', $post);
else
$this->error('错误的记录');
}
$this->display('Post/'.$resource);
}else{
$this->error('错误的请求');
}
}else{
switch (strtolower(CONTROLLER_NAME)) {
case 'post':
echo 'post';die;
$Index = new IndexController();
$Index->detail(ACTION_NAME);
break;
case 'search':
$Index = new IndexController();
$Index->search();
break;
case 'feed':
$type = I('get.type');
$this->feed($type);
break;
case 'mine':
if(!is_login())
$this->error('尚未登录,请登录后再访问', "User/login");
$Index = new IndexController();
$Index->mine();
break;
default:
$Index = new IndexController();
if (is_numeric(CONTROLLER_NAME) && is_numeric(ACTION_NAME)) {
$Index->archive(CONTROLLER_NAME,ACTION_NAME);
}else{
$this->error('错误的请求');
}
break;
}
}
}
}
|
Java
|
/*
* Copyright 2015 Suprema(biostar2@suprema.co.kr)
*
* 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 <UIKit/UIKit.h>
@interface TimeCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *expireTimeLabel;
@end
|
Java
|
<?php
/*------------------------------------------------------------------------
# TZ Portfolio Extension
# ------------------------------------------------------------------------
# author DuongTVTemPlaza
# copyright Copyright (C) 2012 templaza.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.templaza.com
# Technical Support: Forum - http://templaza.com/Forum
-------------------------------------------------------------------------*/
defined('_JEXEC') or die();
$item = $this -> item;
$media = $this -> listMedia;
$params = $this -> mediaParams;
if($params -> get('portfolio_image_size','S')){
if(!empty($media[0] -> images)){
$src = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),'_'.$params -> get('portfolio_image_size','S')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
}
}
?>
<?php if($media):?>
<?php if($media[0] -> type == 'image'):?>
<?php
$src2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),
'_'.$params -> get('detail_article_image_size','XL')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
?>
<?php if($params -> get('show_image',1) == 1 AND !empty($media[0] -> images)):?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $src;?>" data-largesrc="<?php echo$src2;?>"
alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"
title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php if($media[0] -> type == 'imagegallery'):?>
<?php
$srcGallery2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),
'_'.$params -> get('detail_article_image_gallery_size','XL')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
?>
<?php if($params -> get('show_image_gallery',1) == 1 AND !empty($media[0] -> images)):?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $src;?>" data-largesrc="<?php echo $srcGallery2;?>"
alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"
title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php
if($media[0] -> type == 'video'):
if($params -> get('show_video',1) == 1 AND !empty($media[0] -> thumb)):
$srcVideo = str_replace('.'.JFile::getExt($media[0] -> thumb),'_'
.$params -> get('portfolio_image_size','M')
.'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb);
$srcVideo2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> thumb),
'_'.$params -> get('detail_article_image_size','XL')
.'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb);
?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $srcVideo;?>"
data-largesrc="<?php echo $srcVideo2;?>"
title="<?php echo $media[0] -> imagetitle;?>"
alt="<?php echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php endif;?>
|
Java
|
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Gallio.Model.Filters
{
internal class FilterToken
{
private readonly FilterTokenType type;
private readonly string text;
private readonly int position;
internal FilterToken(FilterTokenType type, string text, int position)
{
this.type = type;
this.text = text;
this.position = position;
}
public FilterTokenType Type
{
get { return type; }
}
public string Text
{
get { return text; }
}
public int Position
{
get { return position; }
}
}
}
|
Java
|
package org.jetbrains.plugins.scala.lang.psi.api.base
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement
/**
* @author Alexander Podkhalyuzin
* Date: 22.02.2008
*/
trait ScIdList extends ScalaPsiElement {
def fieldIds: Seq[ScFieldId]
}
|
Java
|
<?php
/**
* Unbind ...
*
* @phpstub
*
* @param resource $connection
* @param string $trigger_name
*
* @return bool
*/
function cyrus_unbind($connection, $trigger_name)
{
}
|
Java
|
ngDefine(
'cockpit.plugin.statistics-plugin.controllers',
function(module) {
module
.controller(
'processDefinitionCtrl',
[
'$scope',
'DataFactory',
'Uri',
function($scope, DataFactory, Uri) {
$scope.options = {
chart : {
type : 'pieChart',
height : 500,
x : function(d) {
return d.key;
},
y : function(d) {
return d.y;
},
showLabels : true,
transitionDuration : 500,
labelThreshold : 0.01,
tooltips : true,
tooltipContent : function(key, y, e, graph) {
if (key == "finished") {
return '<h3>' + key + '</h3>' + '<p>count:<b>' + y
+ '</b><br/>' + 'average Duration:<b>'
+ (e.point.avg / 1000 / 60).toFixed(2)
+ ' min</b><br/>minimal Duration:<b>'
+ (e.point.min / 1000 / 60).toFixed(2)
+ ' min</b><br/>maximal Duration:<b>'
+ (e.point.max / 1000 / 60).toFixed(2)
+ ' min</b></p>'
} else {
return '<h3>' + key + '</h3>' + '<p>' + y + '</p>'
}
},
noData : "No Processes met the requirements",
legend : {
margin : {
top : 5,
right : 5,
bottom : 5,
left : 5
}
}
}
};
DataFactory
.getAllProcessInstanceCountsByState(
$scope.processDefinition.key)
.then(
function() {
var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key];
var counts = [];
counts
.push({
"key" : "running",
"y" : processDefinitionCounts[0].runningInstanceCount
});
counts
.push({
"key" : "failed",
"y" : processDefinitionCounts[0].failedInstanceCount
});
counts
.push({
"key" : "finished",
"y" : processDefinitionCounts[0].endedInstanceCount,
"avg" : processDefinitionCounts[0].duration,
"min" : processDefinitionCounts[0].minDuration,
"max" : processDefinitionCounts[0].maxDuration
});
$scope.statesOfDefinition = counts;
});
} ]);
});
|
Java
|
# Pedicularis rotundifolia C.E.C.Fisch. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
/* Copyright 2015 ETH Zurich
*
* 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 <math.h>
#include "Mutex.h"
#include "PathState.h"
#include "Utils.h"
/* calculate the cubic root of x using a table lookup followed by one
* Newton-Raphson iteration.
* Avg err ~= 0.195%
*
* Taken (and slightly modified) from Linux TCP Cubic implementation
*/
static uint32_t cubeRoot(uint64_t a)
{
uint32_t x, b, shift;
uint64_t c;
/*
* cbrt(x) MSB values for x MSB values in [0..63].
* Precomputed then refined by hand - Willy Tarreau
*
* For x in [0..63],
* v = cbrt(x << 18) - 1
* cbrt(x) = (v[x] + 10) >> 6
*/
static const uint8_t v[] = {
/* 0x00 */ 0, 54, 54, 54, 118, 118, 118, 118,
/* 0x08 */ 123, 129, 134, 138, 143, 147, 151, 156,
/* 0x10 */ 157, 161, 164, 168, 170, 173, 176, 179,
/* 0x18 */ 181, 185, 187, 190, 192, 194, 197, 199,
/* 0x20 */ 200, 202, 204, 206, 209, 211, 213, 215,
/* 0x28 */ 217, 219, 221, 222, 224, 225, 227, 229,
/* 0x30 */ 231, 232, 234, 236, 237, 239, 240, 242,
/* 0x38 */ 244, 245, 246, 248, 250, 251, 252, 254,
};
/* Probably not the fastest way but works without using asm */
b = 0;
c = a;
while (c >>= 1)
b++;
b++;
if (b < 7) {
/* a in [0..63] */
return ((uint32_t)v[(uint32_t)a] + 35) >> 6;
}
b = ((b * 84) >> 8) - 1;
shift = (a >> (b * 3));
x = ((uint32_t)(((uint32_t)v[shift] + 10) << b)) >> 6;
/*
* Newton-Raphson iteration
* 2
* x = ( 2 * x + a / x ) / 3
* k+1 k k
*/
x = 2 * x + (uint32_t)(a / ((uint64_t)x * (uint64_t)(x - 1)));
x = ((x * 341) >> 10);
return x;
}
PathState::PathState(int rtt, int mtu)
: mPathIndex(-1),
mMTU(mtu),
mSRTT(rtt),
mLastRTT(rtt),
mSendWindow(2),
mCongestionWindow(1),
mWindow(1),
mInFlight(0),
mCurrentBurst(0),
mInLoss(false),
mTotalSent(0),
mTotalAcked(0),
mLastTotalAcked(0),
mTotalLost(0),
mAverageLossInterval(0)
{
mVAR = rtt >> VAR_SHIFT;
mRTO = mSRTT + (mVAR << 2);
mSRTT = 0; // initial RTT estimate used for RTO only
memset(mLossBursts, 0, sizeof(mLossBursts));
Mutex mMutex;
}
PathState::~PathState()
{
}
void PathState::setIndex(int index)
{
mPathIndex = index;
}
void PathState::setRemoteWindow(uint32_t sendWindow)
{
mSendWindow = sendWindow;
DEBUG("send window set to %d\n", mSendWindow);
}
int PathState::timeUntilReady()
{
return 0;
}
int PathState::bandwidth()
{
if (mSRTT == 0)
return 0;
return mWindow * mMTU / mSRTT * 1000000;
}
int PathState::estimatedRTT() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mSRTT;
mMutex.Unlock();
return ret;
}
int PathState::getRTO() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mRTO;
mMutex.Unlock();
return ret;
}
int PathState::packetsInFlight() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mInFlight;
mMutex.Unlock();
return ret;
}
double PathState::getLossRate() EXCLUDES(mMutex)
{
mMutex.Lock();
uint64_t currentInterval = mTotalAcked - mLastTotalAcked;
if (currentInterval > mAverageLossInterval) {
if (currentInterval > 2 * mAverageLossInterval)
calculateLoss(ALI_HISTORY_DISCOUNTING);
else
calculateLoss(ALI_FROM_INTERVAL_0);
}
mMutex.Unlock();
if (mAverageLossInterval == 0)
return 0.0;
return 1.0 / mAverageLossInterval;
}
void PathState::addLoss(uint64_t packetNum) EXCLUDES(mMutex)
{
mTotalLost++;
mMutex.Lock();
mInFlight--;
mMutex.Unlock();
mCurrentBurst++;
mInLoss = true;
if (mCurrentBurst == SSP_MAX_LOSS_BURST) {
mLossBursts[SSP_MAX_LOSS_BURST - 1]++;
mCurrentBurst = 0;
mInLoss = false;
}
}
void PathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMutex)
{
mTotalAcked++;
mMutex.Lock();
mInFlight--;
DEBUG("path %d: receive ack: %d packets now in flight\n", mPathIndex, mInFlight);
if (rtt > 0) {
mLastRTT = rtt;
if (mSRTT == 0) {
mSRTT = rtt;
mVAR = rtt >> 1;
} else {
int err = rtt - mSRTT;
mSRTT += err >> ERR_SHIFT;
err = err >= 0 ? err : -err;
mVAR += (err - mVAR) >> VAR_SHIFT;
}
mRTO = mSRTT + (mVAR << 2);
if (mRTO > SSP_MAX_RTO)
mRTO = SSP_MAX_RTO;
DEBUG("path %d: RTT sample %d us, sRTT = %d us, RTO = %d us\n", mPathIndex, rtt, mSRTT, mRTO);
}
if (mInLoss) {
mLossBursts[mCurrentBurst]++;
mCurrentBurst = 0;
mInLoss = false;
}
mMutex.Unlock();
}
void PathState::addRetransmit() EXCLUDES(mMutex)
{
mMutex.Lock();
mLossIntervals.push_front(mTotalAcked - mLastTotalAcked);
if (mLossIntervals.size() > MAX_LOSS_INTERVALS)
mLossIntervals.pop_back();
DEBUG("loss on path %d: new loss interval = %ld, %d/%d in flight\n",
mPathIndex, mTotalAcked - mLastTotalAcked, mInFlight, mWindow);
mLastTotalAcked = mTotalAcked;
calculateLoss(ALI_FROM_INTERVAL_1);
mMutex.Unlock();
}
void PathState::handleSend(uint64_t packetNum) EXCLUDES(mMutex)
{
mMutex.Lock();
mInFlight++;
mTotalSent++;
DEBUG("path %d: send: %d/%d packets now in flight\n", mPathIndex, mInFlight, mWindow);
mMutex.Unlock();
}
void PathState::handleTimeout() EXCLUDES(mMutex)
{
mMutex.Lock();
mRTO = mRTO << 1;
if (mRTO > SSP_MAX_RTO)
mRTO = SSP_MAX_RTO;
DEBUG("timeout: new rto = %d\n", mRTO);
mMutex.Unlock();
}
void PathState::handleDupAck()
{
}
void PathState::calculateLoss(ALIType type)
{
if (mLossIntervals.empty())
return;
uint64_t currentInterval = mTotalAcked - mLastTotalAcked;
size_t i;
list<uint64_t>::iterator it;
size_t n = mLossIntervals.size();
double ws = 0.0;
double w = 0.0;
double d[MAX_LOSS_INTERVALS + 1];
double di = 2.0 * mAverageLossInterval / currentInterval;
double wi;
DEBUG("calculate average loss interval (%d), currentInterval = %ld\n", type, currentInterval);
if (di < 0.5)
di = 0.5;
for (i = 0; i <= MAX_LOSS_INTERVALS; i++)
d[i] = 1.0;
switch (type) {
case ALI_HISTORY_DISCOUNTING:
for (i = 1; i < MAX_LOSS_INTERVALS; i++)
d[i] = di;
case ALI_FROM_INTERVAL_0:
mLossIntervals.push_front(currentInterval);
case ALI_FROM_INTERVAL_1:
for (it = mLossIntervals.begin(), i = 1; it != mLossIntervals.end() && i < MAX_LOSS_INTERVALS; it++, i++) {
if (i <= n / 2) {
ws += d[i - 1] * (*it);
w += d[i - 1];
} else {
wi = 1 - (i - n / 2.0) / (n / 2.0 + 1);
ws += d[i - 1] * wi * (*it);
w += d[i - 1] * wi;
}
}
break;
default:
break;
}
if (type != ALI_FROM_INTERVAL_1)
mLossIntervals.pop_front();
mAverageLossInterval = ws / w;
DEBUG("average loss interval = %ld\n", mAverageLossInterval);
}
bool PathState::isWindowBased()
{
return false;
}
int PathState::window()
{
return 0;
}
int PathState::profileLoss()
{
double p, q;
int m = 0;
for (int i = 1; i < SSP_MAX_LOSS_BURST; i++)
m += mLossBursts[i];
p = (double)m / mTotalAcked;
int mi1 = 0, mi2 = 0;
for (int i = 2; i < SSP_MAX_LOSS_BURST; i++)
mi2 += mLossBursts[i] * (i - 1);
for (int i = 1; i < SSP_MAX_LOSS_BURST; i++)
mi1 += mLossBursts[i] * i;
q = 1 - (double)mi2 / mi1;
printf("p = %f, q = %f\n", p, q);
return 0;
}
// CBR
CBRPathState::CBRPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mSendInterval(SSP_SEND_INTERVAL)
{
memset(&mLastSendTime, 0, sizeof(mLastSendTime));
}
int CBRPathState::timeUntilReady()
{
if (mLastSendTime.tv_sec == 0)
return 0;
struct timeval current;
gettimeofday(¤t, NULL);
DEBUG("%ld us since last send\n", elapsedTime(&mLastSendTime, ¤t));
int time = mSendInterval - elapsedTime(&mLastSendTime, ¤t);
if (time < 0)
time = 0;
return time;
}
int CBRPathState::bandwidth()
{
return mMTU / mSendInterval * 1000000;
}
void CBRPathState::handleSend(uint64_t packetNum)
{
PathState::handleSend(packetNum);
gettimeofday(&mLastSendTime, NULL);
}
// PCC
PCCPathState::PCCPathState(int rtt, int mtu)
: CBRPathState(rtt, mtu),
mLastSendInterval(SSP_SEND_INTERVAL),
mMonitorRTT(0.0),
mMonitorReceived(0),
mMonitorLost(0),
mMonitoring(false),
mUtility(0.0),
mCurrentTrial(0),
mAdjustCount(0),
mDirection(0),
mState(PCC_START)
{
memset(&mMonitorStartTime, 0, sizeof(mMonitorStartTime));
memset(&mMonitorEndTime, 0, sizeof(mMonitorEndTime));
memset(mTrialResults, 0, sizeof(mTrialResults));
memset(mTrialIntervals, 0, sizeof(mTrialIntervals));
Mutex mMonitorMutex;
}
int PCCPathState::timeUntilReady()
{
int currentInterval = mSendInterval;
if (mState == PCC_DECISION)
mSendInterval = mTrialIntervals[mCurrentTrial];
int res = CBRPathState::timeUntilReady();
mSendInterval = currentInterval;
return res;
}
void PCCPathState::handleSend(uint64_t packetNum) EXCLUDES(mMonitorMutex)
{
struct timeval t;
gettimeofday(&t, NULL);
CBRPathState::handleSend(packetNum);
if (!mMonitoring) {
DEBUG("%ld.%06ld: current state = %d, begin monitoring\n", t.tv_sec, t.tv_usec, mState);
mMonitorStartTime = t;
srand(t.tv_usec);
double x = (double)rand() / RAND_MAX; // 0 ~ 1.0
x /= 2.0; // 0 ~ 0.5
x += 1.7; // 1.7 ~ 2.2
mMonitorDuration = x * mSRTT;
if (mMonitorDuration < PCC_MIN_PACKETS * mSendInterval)
mMonitorDuration = PCC_MIN_PACKETS * mSendInterval;
mMonitorRTT = 0;
mMonitorReceived = 0;
mMonitorLost = 0;
mMonitoring = true;
}
if (mMonitoring) {
if (elapsedTime(&mMonitorStartTime, &t) < mMonitorDuration ) {
mMonitorMutex.Lock();
mMonitoredPackets.insert(packetNum);
mMonitorMutex.Unlock();
}
}
}
void PCCPathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMonitorMutex)
{
PathState::addRTTSample(rtt, packetNum);
if (mMonitoring) {
bool found = false;
mMonitorMutex.Lock();
found = mMonitoredPackets.find(packetNum) != mMonitoredPackets.end();
mMonitorMutex.Unlock();
if (found) {
mMonitorReceived++;
mMonitorRTT += rtt;
DEBUG("current state = %d: got ack %ld\n", mState, packetNum);
}
}
struct timeval t;
gettimeofday(&t, NULL);
if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT)
handleMonitorEnd();
}
void PCCPathState::addLoss(uint64_t packetNum)
{
PathState::addLoss(packetNum);
struct timeval t;
gettimeofday(&t, NULL);
if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT)
handleMonitorEnd();
}
void PCCPathState::handleMonitorEnd() EXCLUDES(mMonitorMutex)
{
if (!mMonitoring)
return;
mMonitorMutex.Lock();
gettimeofday(&mMonitorEndTime, NULL);
DEBUG("%ld.%06ld: monitor end\n", mMonitorEndTime.tv_sec, mMonitorEndTime.tv_usec);
long monitorTime = elapsedTime(&mMonitorStartTime, &mMonitorEndTime);
if (mMonitorReceived == 0) {
mMonitorRTT = SSP_MAX_RTO;
} else {
mMonitorRTT /= mMonitorReceived;
}
DEBUG("%lu packets sent during this interval, %lu received\n", mMonitoredPackets.size(), mMonitorReceived);
mMonitorLost = mMonitoredPackets.size() - mMonitorReceived;
double u = utility(mMonitorReceived, mMonitorLost, monitorTime / 1000000.0, mMonitorRTT);
DEBUG("utility %f\n", u);
if (mState == PCC_DECISION) {
DEBUG("decision phase, trial %d\n", mCurrentTrial);
mTrialResults[mCurrentTrial++] = u;
if (mCurrentTrial == PCC_TRIALS) {
int direction = 0;
for (int i = 0; i < PCC_TRIALS - 1; i += 2) {
if (mTrialIntervals[i] < mSendInterval) {
// i: shorter period, i + 1: longer period
if (mTrialResults[i] > mTrialResults[i + 1])
direction--;
else if (mTrialResults[i] < mTrialResults[i + 1])
direction++;
} else {
// i: longer period, i + 1: shorter period
if (mTrialResults[i] > mTrialResults[i + 1])
direction++;
else if (mTrialResults[i] < mTrialResults[i + 1])
direction--;
}
}
if (direction == 0) {
DEBUG("inconclusive, do over with larger deltas\n");
mAdjustCount++;
if (mAdjustCount > PCC_MAX_ADJUST_COUNT)
mAdjustCount = PCC_MAX_ADJUST_COUNT;
startDecision();
} else {
mDirection = direction / 2; // direction = +-2, mDirection = +-1
mState = PCC_ADJUST;
mLastSendInterval = mSendInterval;
mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE;
DEBUG("switched to adjust phase, direction = %d with %d us period\n", mDirection, mSendInterval);
}
}
} else if (mState == PCC_ADJUST) {
if (u >= mUtility) {
mAdjustCount++;
if (mAdjustCount > PCC_MAX_ADJUST_COUNT)
mAdjustCount = PCC_MAX_ADJUST_COUNT;
mLastSendInterval = mSendInterval;
mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE;
DEBUG("utility increased, keep going in direction %d with %d us period\n", mDirection, mSendInterval);
} else {
mSendInterval = mLastSendInterval;
mAdjustCount = 1;
DEBUG("utility decreased, drop back to decision phase with %d us period\n", mSendInterval);
startDecision();
}
mUtility = u;
} else if (mState == PCC_START) {
if (u >= mUtility) {
mLastSendInterval = mSendInterval;
mSendInterval /= 2;
DEBUG("utility increased, double speed: %d us period\n", mSendInterval);
} else {
mSendInterval = mLastSendInterval;
mAdjustCount = 1;
DEBUG("utility decreased, drop down to decision phase with %d us period\n", mSendInterval);
startDecision();
}
mUtility = u;
}
if (mSendInterval > SSP_MAX_SEND_INTERVAL)
mSendInterval = SSP_MAX_SEND_INTERVAL;
mMonitoredPackets.clear();
mMonitoring = false;
if (mMonitorReceived == 0)
mSendInterval *= 2;
mMonitorMutex.Unlock();
}
void PCCPathState::startDecision()
{
srand(time(NULL));
for (int i = 0; i < PCC_TRIALS - 1; i += 2) {
int delta = (rand() % 2) * 2 - 1;
delta *= mAdjustCount * PCC_ADJUST_RATE * mSendInterval;
mTrialIntervals[i] = mSendInterval + delta;
mTrialIntervals[i + 1] = mSendInterval - delta;
}
mCurrentTrial = 0;
mState = PCC_DECISION;
}
double PCCPathState::utility(int received, int lost, double time, double rtt)
{
DEBUG("%d %d %f %f\n", received, lost, time, rtt);
//utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))-1*l/time);
//utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))* (1-1/(1+exp(-10*(1-previous_rtt/rtt)))) -1*l/time)/rtt*1000;
return received / time * (1 - 1 / (1 + exp(-100 * (lost / (received + lost) - 0.05)))) - lost / time;
}
// TCP Reno
RenoPathState::RenoPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mState(TCP_STATE_START),
mThreshold(-1),
mDupAckCount(0),
mAckCount(0)
{
}
int RenoPathState::timeUntilReady()
{
if (mInFlight < mWindow) {
DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow);
return 0;
} else {
DEBUG("path %d: window full, wait about 1 RTT (%d us)\n", mPathIndex, mSRTT);
return mSRTT ? mSRTT : mRTO;
}
}
void RenoPathState::handleTimeout()
{
PathState::handleTimeout();
mState = TCP_STATE_TIMEOUT;
mCongestionWindow = 1;
DEBUG("path %d: timeout: congestion window set to 1\n", mPathIndex);
}
void RenoPathState::handleDupAck()
{
mDupAckCount++;
if (mState > SSP_FR_THRESHOLD && mState == TCP_STATE_FAST_RETRANSMIT) {
mCongestionWindow++;
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: duplicate ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
}
void RenoPathState::addRTTSample(int rtt, uint64_t packetNum)
{
PathState::addRTTSample(rtt, packetNum);
mDupAckCount = 0;
mAckCount++;
switch (mState) {
case TCP_STATE_START:
case TCP_STATE_TIMEOUT:
DEBUG("path %d: slow start: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1);
mCongestionWindow++;
if (mCongestionWindow == mThreshold) {
DEBUG("path %d: reached threshold: %d\n", mPathIndex, mThreshold);
mState = TCP_STATE_NORMAL;
}
break;
case TCP_STATE_FAST_RETRANSMIT:
mState = TCP_STATE_NORMAL;
mCongestionWindow = mThreshold;
break;
case TCP_STATE_NORMAL:
if (mAckCount == mCongestionWindow) {
DEBUG("path %d: congestion avoidance: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1);
mAckCount = 0;
mCongestionWindow++;
}
break;
default:
break;
}
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
void RenoPathState::addRetransmit()
{
PathState::addRetransmit();
mThreshold = mWindow >> 1;
if (mThreshold < 2)
mThreshold = 2;
mAckCount = 0;
if (mState != TCP_STATE_TIMEOUT && mState != TCP_STATE_FAST_RETRANSMIT) {
mState = TCP_STATE_FAST_RETRANSMIT;
mCongestionWindow = mThreshold + 3;
}
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: packet loss: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
bool RenoPathState::isWindowBased()
{
return true;
}
int RenoPathState::window()
{
return mWindow;
}
// TCP CUBIC
CUBICPathState::CUBICPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mThreshold(-1),
mTimeout(false)
{
reset();
}
int CUBICPathState::timeUntilReady() EXCLUDES(mMutex)
{
mMutex.Lock();
if (mInFlight < mWindow) {
DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow);
mMutex.Unlock();
return 0;
} else {
DEBUG("path %d: window full (%d/%d), wait about 1 RTT (%d us)\n", mPathIndex, mInFlight, mWindow, mSRTT);
mMutex.Unlock();
return mSRTT ? mSRTT : mRTO;
}
}
void CUBICPathState::addRTTSample(int rtt, uint64_t packetNum)
{
PathState::addRTTSample(rtt, packetNum);
if (rtt == 0)
return;
mTimeout = false;
if (mMinDelay == 0 || mMinDelay > rtt)
mMinDelay = rtt;
mAckCount++;
int thresh = mThreshold > 0 ? mThreshold : CUBIC_SSTHRESH;
if (mCongestionWindow < thresh) {
mCongestionWindow++;
DEBUG("path %d: slow start, increase to %d\n", mPathIndex, mCongestionWindow);
} else {
update();
DEBUG("path %d: congestion avoidance (%d/%d)\n", mPathIndex, mWindowCount, mCount);
if (mWindowCount > mCount) {
mCongestionWindow++;
DEBUG("path %d: increase window to %d\n", mPathIndex, mCongestionWindow);
mWindowCount = 0;
} else {
mWindowCount++;
}
}
mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow;
DEBUG("path %d: ack received: window set to %d (%d|%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
void CUBICPathState::addRetransmit() EXCLUDES(mMutex)
{
PathState::addRetransmit();
mEpochStart = 0;
if (mCongestionWindow < mMaxWindow)
mMaxWindow = mCongestionWindow * (2 - BETA) / 2;
else
mMaxWindow = mCongestionWindow;
mCongestionWindow *= (1 - BETA);
if (mCongestionWindow < 1)
mCongestionWindow = 1;
mThreshold = mCongestionWindow;
if (mTimeout)
mCongestionWindow = 1;
mMutex.Lock();
mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow;
mMutex.Unlock();
DEBUG("path %d: packet loss: window set to %d (last max window %d)\n", mPathIndex, mWindow, mMaxWindow);
}
void CUBICPathState::handleSend(uint64_t packetNum)
{
PathState::handleSend(packetNum);
}
void CUBICPathState::handleTimeout()
{
PathState::handleTimeout();
mTimeout = true;
mThreshold = (1 - BETA) * mCongestionWindow;
reset();
DEBUG("path %d: timeout: congestion window dropped to 1\n", mPathIndex);
}
void CUBICPathState::reset()
{
mWindowCount = 0;
mAckCount = 0;
mMinDelay = 0;
mMaxWindow = 0;
mTCPWindow = 0;
mOrigin = 0;
mCount = 0;
mK = 0;
mEpochStart = 0;
}
void CUBICPathState::doTCPFriendly()
{
mTCPWindow += 3 * BETA / (2 - BETA) * mAckCount / mCongestionWindow;
mAckCount = 0;
if (mTCPWindow > mCongestionWindow) {
if (mCount > mCongestionWindow / (mTCPWindow - mCongestionWindow))
mCount = mCongestionWindow / (mTCPWindow - mCongestionWindow);
}
}
void CUBICPathState::update()
{
time_t timestamp = time(NULL);
if (mEpochStart == 0) {
mEpochStart = timestamp;
if (mCongestionWindow < mMaxWindow) {
mK = cubeRoot((mMaxWindow - mCongestionWindow) / C);
mOrigin = mMaxWindow;
} else {
mK = 0;
mOrigin = mCongestionWindow;
}
mAckCount = 1;
mTCPWindow = mCongestionWindow;
}
int t = timestamp + mMinDelay / 1000000 - mEpochStart;
int x = t - mK;
int target = mOrigin + C * x * x * x;
if (target > mCongestionWindow)
mCount = mCongestionWindow / (target - mCongestionWindow);
else
mCount = 100 * mCongestionWindow;
doTCPFriendly();
}
bool CUBICPathState::isWindowBased()
{
return true;
}
int CUBICPathState::window()
{
return mWindow;
}
|
Java
|
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { UserData } from './user-data';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
@Injectable()
export class ConferenceData {
data: any;
constructor(public http: Http, public user: UserData) { }
load(): any {
if (this.data) {
return Observable.of(this.data);
} else {
return this.http.get('assets/data/data.json')
.map(this.processData, this);
}
}
processData(data: any) {
// just some good 'ol JS fun with objects and arrays
// build up the data by linking employees to sessions
this.data = data.json();
this.data.tracks = [];
// loop through each day in the schedule
this.data.schedule.forEach((day: any) => {
// loop through each timeline group in the day
day.groups.forEach((group: any) => {
// loop through each session in the timeline group
group.sessions.forEach((session: any) => {
session.employees = [];
if (session.employeeNames) {
session.employeeNames.forEach((employeeName: any) => {
let employee = this.data.employees.find((s: any) => s.name === employeeName);
if (employee) {
session.employees.push(employee);
employee.sessions = employee.sessions || [];
employee.sessions.push(session);
}
});
}
if (session.tracks) {
session.tracks.forEach((track: any) => {
if (this.data.tracks.indexOf(track) < 0) {
this.data.tracks.push(track);
}
});
}
});
});
});
return this.data;
}
getTimeline(dayIndex: number, queryText = '', excludeTracks: any[] = [], segment = 'all') {
return this.load().map((data: any) => {
let day = data.schedule[dayIndex];
day.shownSessions = 0;
queryText = queryText.toLowerCase().replace(/,|\.|-/g, ' ');
let queryWords = queryText.split(' ').filter(w => !!w.trim().length);
day.groups.forEach((group: any) => {
group.hide = true;
group.sessions.forEach((session: any) => {
// check if this session should show or not
this.filterSession(session, queryWords, excludeTracks, segment);
if (!session.hide) {
// if this session is not hidden then this group should show
group.hide = false;
day.shownSessions++;
}
});
});
return day;
});
}
filterSession(session: any, queryWords: string[], excludeTracks: any[], segment: string) {
let matchesQueryText = false;
if (queryWords.length) {
// of any query word is in the session name than it passes the query test
queryWords.forEach((queryWord: string) => {
if (session.name.toLowerCase().indexOf(queryWord) > -1) {
matchesQueryText = true;
}
});
} else {
// if there are no query words then this session passes the query test
matchesQueryText = true;
}
// if any of the sessions tracks are not in the
// exclude tracks then this session passes the track test
let matchesTracks = false;
session.tracks.forEach((trackName: string) => {
if (excludeTracks.indexOf(trackName) === -1) {
matchesTracks = true;
}
});
// if the segement is 'favorites', but session is not a user favorite
// then this session does not pass the segment test
let matchesSegment = false;
if (segment === 'favorites') {
if (this.user.hasFavorite(session.name)) {
matchesSegment = true;
}
} else {
matchesSegment = true;
}
// all tests must be true if it should not be hidden
session.hide = !(matchesQueryText && matchesTracks && matchesSegment);
}
getEmployees() {
return this.load().map((data: any) => {
return data.employees.sort((a: any, b: any) => {
let aName = a.name.split(' ').pop();
let bName = b.name.split(' ').pop();
return aName.localeCompare(bName);
});
});
}
getTracks() {
return this.load().map((data: any) => {
return data.tracks.sort();
});
}
getMap() {
return this.load().map((data: any) => {
return data.map;
});
}
}
|
Java
|
/**
* Red Hat Open Innovation Labs API
* A generic model to support automation at all levels of the application and infrastructure lifecycle.
*
* OpenAPI spec version: 0.3.0-alpha
* Contact: rhc-open-innovation-labs@redhat.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Port'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Port'));
} else {
// Browser globals (root is window)
if (!root.RedHatOpenInnovationLabsApi) {
root.RedHatOpenInnovationLabsApi = {};
}
root.RedHatOpenInnovationLabsApi.Service = factory(root.RedHatOpenInnovationLabsApi.ApiClient, root.RedHatOpenInnovationLabsApi.Port);
}
}(this, function(ApiClient, Port) {
'use strict';
/**
* The Service model module.
* @module model/Service
* @version 0.3.0-alpha
*/
/**
* Constructs a new <code>Service</code>.
* @alias module:model/Service
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>Service</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Service} obj Optional instance to populate.
* @return {module:model/Service} The populated <code>Service</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('ports')) {
obj['ports'] = ApiClient.convertToType(data['ports'], [Port]);
}
}
return obj;
}
/**
* @member {Number} id
*/
exports.prototype['id'] = undefined;
/**
* @member {String} name
*/
exports.prototype['name'] = undefined;
/**
* @member {Array.<module:model/Port>} ports
*/
exports.prototype['ports'] = undefined;
return exports;
}));
|
Java
|
package nl.esciencecenter.e3dchem.modifiedtanimoto;
import org.knime.base.util.flowvariable.FlowVariableProvider;
import org.knime.core.data.DataTableSpec;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.util.CheckUtils;
import org.knime.distance.category.DistanceCategoryConfig;
import org.knime.distance.util.propertyresolver.Configuration;
import org.knime.distance.util.propertyresolver.Property;
@Configuration
public final class ModifiedTanimotoDistanceConfig extends
DistanceCategoryConfig<ModifiedTanimotoDistance> {
@Property("meanBitDensity")
private double meanBitDensity = 0.01;
/**
* Framework constructor.
*/
ModifiedTanimotoDistanceConfig() {
}
public ModifiedTanimotoDistanceConfig(final double meanBitDensity,
String column) throws InvalidSettingsException {
super(column);
this.meanBitDensity = meanBitDensity;
CheckUtils.checkSetting(meanBitDensity >= 0,
"mean bit density is not positive: %f ", meanBitDensity);
}
@Override
protected DistanceCategoryConfig<?> clone(String... columns)
throws InvalidSettingsException {
CheckUtils.checkSetting(columns != null && columns.length == 1,
"Exactly one column must be selected.");
return new ModifiedTanimotoDistanceConfig(meanBitDensity, columns[0]);
}
@Override
public String getFactoryId() {
return ModifiedTanimotoDistanceFactory.ID;
}
/**
* {@inheritDoc}
*/
@Override
public ModifiedTanimotoDistance createDistanceMeasure(DataTableSpec spec,
FlowVariableProvider flowVariableProvider)
throws InvalidSettingsException {
return new ModifiedTanimotoDistance(this, spec);
}
public double getMeanBitDensity() {
return meanBitDensity;
}
public void setMeanBitDensity(final double meanBitDensity) {
this.meanBitDensity = meanBitDensity;
}
}
|
Java
|
# Zygophyllum novae-zeelandiae Steud. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using RElmah.Common.Model;
using RElmah.Errors;
using RElmah.Services.Nulls;
namespace RElmah.Services.Inbox
{
public class SerializedErrorsInbox : IErrorsInbox
{
private readonly IErrorsBacklog _errorsBacklog;
private readonly Subject<ErrorPayload> _errors;
private readonly IObservable<ErrorPayload> _publishedErrors;
public SerializedErrorsInbox() : this(NullErrorsBacklog.Instance) { }
public SerializedErrorsInbox(IErrorsBacklog errorsBacklog)
{
_errorsBacklog = errorsBacklog;
_errors = new Subject<ErrorPayload>();
_publishedErrors = _errors.Publish().RefCount();
}
public Task Post(ErrorPayload payload)
{
return _errorsBacklog
.Store(payload)
.ContinueWith(_ => _errors.OnNext(payload));
}
public IObservable<ErrorPayload> GetErrorsStream()
{
return _publishedErrors;
}
}
}
|
Java
|
# Lichtheimia hongkongensis K.Y. Yuen, 2009 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/orange-pi-one-debian:buster-run
ENV NODE_VERSION 15.14.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "1cef461a73a124dd3f212e2b8230638f4d16b5cc0915425ffad8aabac050d9fb node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
#!/usr/bin/env sh
set -e
exit 0
SCALA_VERSION=${SCALA_VERSION:-2_12}
sbt \
grpcRuntimeJVM${SCALA_VERSION}/mimaReportBinaryIssues \
lensesJVM${SCALA_VERSION}/mimaReportBinaryIssues \
runtimeJVM${SCALA_VERSION}/mimaReportBinaryIssues \
compilerPluginJVM${SCALA_VERSION}/mimaReportBinaryIssues
|
Java
|
#!/usr/bin/env bash
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#
#
# A script to run multiple GPU tests in parallel controlled with an environment
# variable.
#
# Required environment variables:
# TF_GPU_COUNT = Number of GPUs available.
TF_GPU_COUNT=${TF_GPU_COUNT:-4}
TF_TESTS_PER_GPU=${TF_TESTS_PER_GPU:-8}
# We want to allow running one of the following configs:
# - 4 tests per GPU on k80
# - 8 tests per GPU on p100
# p100 has minimum 12G memory. Therefore, we should limit each test to 1.5G.
# To leave some room in case we want to run more tests in parallel in the
# future and to use a rounder number, we set it to 1G.
export TF_PER_DEVICE_MEMORY_LIMIT_MB=${TF_PER_DEVICE_MEMORY_LIMIT_MB:-1024}
# *******************************************************************
# This section of the script is needed to
# make things work on windows under msys.
# *******************************************************************
RUNFILES_MANIFEST_FILE="${TEST_SRCDIR}/MANIFEST"
function rlocation() {
if is_absolute "$1" ; then
# If the file path is already fully specified, simply return it.
echo "$1"
elif [[ -e "$TEST_SRCDIR/$1" ]]; then
# If the file exists in the $TEST_SRCDIR then just use it.
echo "$TEST_SRCDIR/$1"
elif [[ -e "$RUNFILES_MANIFEST_FILE" ]]; then
# If a runfiles manifest file exists then use it.
echo "$(grep "^$1 " "$RUNFILES_MANIFEST_FILE" | sed 's/[^ ]* //')"
fi
}
TEST_BINARY="$(rlocation $TEST_WORKSPACE/${1#./})"
shift
# *******************************************************************
mkdir -p /var/lock
# Try to acquire any of the TF_GPU_COUNT * TF_TESTS_PER_GPU
# slots to run a test at.
#
# Prefer to allocate 1 test per GPU over 4 tests on 1 GPU.
# So, we iterate over TF_TESTS_PER_GPU first.
for j in `seq 0 $((TF_TESTS_PER_GPU-1))`; do
for i in `seq 0 $((TF_GPU_COUNT-1))`; do
exec {lock_fd}>/var/lock/gpulock${i}_${j} || exit 1
if flock -n "$lock_fd";
then
(
# This export only works within the brackets, so it is isolated to one
# single command.
export CUDA_VISIBLE_DEVICES=$i
export HIP_VISIBLE_DEVICES=$i
echo "Running test $TEST_BINARY $* on GPU $CUDA_VISIBLE_DEVICES"
"$TEST_BINARY" $@
)
return_code=$?
flock -u "$lock_fd"
exit $return_code
fi
done
done
echo "Cannot find a free GPU to run the test $* on, exiting with failure..."
exit 1
|
Java
|
MApps
=====
Mobile App
|
Java
|
(function($) {
module("referenceReads1");
// Test case : Reference Reads 1
_asyncTest("Reference Reads 1", function()
{
expect(6);
GitanaTest.authenticateFullOAuth().then(function() {
var platform = this;
// create a few things
var repository = null;
this.createRepository().then(function() {
repository = this;
});
var domain = null;
this.createDomain().then(function() {
domain = this;
});
var registrar = null;
this.createRegistrar().then(function() {
registrar = this;
});
var stack = null;
this.createStack().then(function() {
stack = this;
});
var team = null;
this.then(function() {
this.subchain(stack).createTeam("abc-" + new Date().getTime()).then(function() {
team = this;
});
});
this.then(function() {
var repositoryReference = "repository://" + platform.getId() + "/" + repository.getId();
var domainReference = "domain://" + platform.getId() + "/" + domain.getId();
var registrarReference = "registrar://" + platform.getId() + "/" + registrar.getId();
var stackReference = "stack://" + platform.getId() + "/" + stack.getId();
var teamReference = "team://stack/" + platform.getId() + "/" + stack.getId() + "/" + team.getKey();
var entries = [{
"ref": repositoryReference
}, {
"ref": domainReference
}, {
"ref": registrarReference
}, {
"ref": stackReference
}, {
"ref": teamReference
}];
this.referenceReads(entries, function(results) {
// check that they all came back
ok(results.length == entries.length, "Found the right number of results");
for (var i = 0; i < results.length; i++)
{
ok(results[i].entry, "Found entry #" + i);
}
// done
start();
});
});
});
});
}(jQuery) );
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<title>Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format (ARX API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format (ARX API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/deidentifier/arx/aggregates/class-use/HierarchyBuilderDate.Format.html" target="_top">Frames</a></li>
<li><a href="HierarchyBuilderDate.Format.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format" class="title">Uses of Class<br>org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.deidentifier.arx.aggregates">org.deidentifier.arx.aggregates</a></td>
<td class="colLast">
<div class="block">This package provides methods for aggregating data.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.deidentifier.arx.aggregates">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a> that return <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#getFormat()">getFormat</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a> with parameters of type <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilder.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilder</a><java.util.Date></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#create(org.deidentifier.arx.DataType, java.util.TimeZone, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format, java.util.Date, java.util.Date, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Granularity...)">create</a></strong>(<a href="../../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a><java.util.Date> type,
java.util.TimeZone timeZone,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format,
java.util.Date bottomCoding,
java.util.Date topCoding,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Granularity.html" title="enum in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Granularity</a>... granularities)</code>
<div class="block">Creates an hierarchy reflecting the given granularities</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilder.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilder</a><java.util.Date></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#create(org.deidentifier.arx.DataType, java.util.TimeZone, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Granularity...)">create</a></strong>(<a href="../../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a><java.util.Date> type,
java.util.TimeZone timeZone,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Granularity.html" title="enum in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Granularity</a>... granularities)</code>
<div class="block">Creates an hierarchy reflecting the given granularities</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#setFormat(org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format)">setFormat</a></strong>(<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/deidentifier/arx/aggregates/class-use/HierarchyBuilderDate.Format.html" target="_top">Frames</a></li>
<li><a href="HierarchyBuilderDate.Format.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.