repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
madfist/aoc2016 | aoc2018/day08/main.py | 2649 | import sys
def sum_metadata(idx, nums):
sum = 0
if (nums[idx] > 0):
for i in range(nums[idx]):
s, idx = sum_metadata(idx+2, nums)
sum += s
else:
for i in range(nums[idx+1]):
sum += nums[idx+2+i]
idx += 2 + nums[idx+1]
return sum, idx
# zero-starting nodes are leaves, sum them,
# remove them from the list and decrease parents node count,
# repeat from beginning
def part1(data):
nums = [int(d) for d in data.split(' ')]
sum = 0
while len(nums) > 0:
for i in range(0, len(nums), 2):
if nums[i] == 0:
for j in range(nums[i+1]):
sum += nums[i+2+j]
nums = nums[:i] + nums[i+2+nums[i+1]:]
if i > 1:
nums[i-2] -= 1
break
return sum
# same as before, but when leaves are removed, convert node count
# into a list, decrease node count and append the sum of the leaf
# from then use the metadata on the inner list when node count
# drops to zero
def part2(data):
nums = [int(d) for d in data.split(' ')]
while len(nums) > 1:
for i in range(0, len(nums), 2):
# print('--- index', i)
sum = 0
if nums[i] == 0:
for j in range(nums[i+1]):
sum += nums[i+2+j]
# print('remove', nums[i:i+2+nums[i+1]], s)
nums = nums[:i] + nums[i+2+nums[i+1]:]
if i > 1:
# print('\tfrom', nums[i-2:i+10])
nums[i-2][0] -= 1
nums[i-2].append(sum)
# print('\tto', nums[i-2:i+10])
break
elif isinstance(nums[i], list) and nums[i][0] == 0:
for j in range(nums[i+1]):
if nums[i+2+j] < len(nums[i]):
sum += nums[i][nums[i+2+j]]
# print('x remove', nums[i:i+2+nums[i+1]], s)
nums = nums[:i] + nums[i+2+nums[i+1]:]
if i > 1:
# print('\tfrom', nums[i-2:i+10])
nums[i-2][0] -= 1
nums[i-2].append(sum)
# print('\tto', nums[i-2:i+10])
break
elif not isinstance(nums[i], list):
nums[i] = [nums[i]]
return sum
def main():
if (len(sys.argv) < 2):
print("Usage python3 %s <input>" % sys.argv[0])
exit(-1)
with open(sys.argv[1], 'r') as input:
data = input.read()
print('part1', part1(data))
print('part2', part2(data))
if __name__ == '__main__':
main()
| mit |
modjs/mod-pageload-reporter | harviewer/scripts/nls/previewTab.js | 731 | /* See license.txt for terms of usage */
define(
{
"root": {
"previewTabLabel": "Preview",
"showTimelineButton": "Show Page Timeline",
"hideTimelineButton": "Hide Page Timeline",
"showTimelineTooltip": "Show/hide statistic preview for selected pages in the timeline.",
"showStatsButton": "Show Statistics",
"hideStatsButton": "Hide Statistics",
"showStatsTooltip": "Show/hide page timeline.",
"clearButton": "Clear",
"clearTooltip": "Remove all HAR logs from the viewer",
"downloadTooltip": "Download all current data in one HAR file.",
"downloadError": "Failed to save HAR data",
"menuShowHARSource": "Show HAR Source"
}
});
| mit |
blinkboxbooks/catalogue-v2.scala | catalogue2-service-public/src/main/scala/com/blinkbox/books/agora/catalogue/contributor/ElasticSearchContributorService.scala | 638 | package com.blinkbox.books.agora.catalogue.contributor
import java.util.concurrent.Executors
import com.blinkbox.books.logging.DiagnosticExecutionContext
import com.typesafe.scalalogging.StrictLogging
import scala.concurrent.{ExecutionContext, Future}
class ElasticSearchContributorService extends ContributorService with StrictLogging {
implicit val executionContext = DiagnosticExecutionContext(ExecutionContext.fromExecutor(Executors.newCachedThreadPool))
override def getContributorById(id: String): Future[Option[Contributor]] = {
Future.successful(Some(Contributor(id, id, "name", "sort-name", 42, "bio", List())))
}
}
| mit |
sazid/codes | problem_solving/codeforces/401C.cpp | 980 | #include <bits/stdc++.h>
using namespace std;
short arr[(int)10e6+5];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
string s;
cin >> n >> m;
if (n-1 <= m and (m <= 2 * (n + 1)))
{
if (n-1 == m)
{
cout << 0;
for(size_t i = 0; i < m; ++i)
{
cout << 10;
}
}
else if (n == m)
{
for (int i = 0; i < n; ++i)
{
cout << 10;
}
}
else
{
const int sz = 2 * n + 1;
memset(arr, 0, sizeof(arr));
for (int i = 0; i < sz; ++i)
{
if (i % 2 == 0 and m > 0)
{
++arr[i];
--m;
}
}
for (int i = 0; i < sz; ++i)
{
if (i % 2 == 0 and m > 0)
{
++arr[i];
--m;
}
}
for (int i = 0; i < sz; ++i)
{
if (i % 2 == 0)
{
if (arr[i] == 1) cout << 1;
if (arr[i] == 2) cout << 11;
}
else
{
cout << 0;
}
}
}
}
else
{
cout << -1;
}
return 0;
}
| mit |
mcrider/aiga-5-0 | client/pages/entry/new_entry.js | 3374 |
Template.new_entry.events({
'click #entryList': function(e) {
e.preventDefault();
Session.set('newEntry', false);
},
'change #type': function(e) {
var type = $(e.currentTarget).val();
$('.project_fields').addClass('hidden');
// Adjust project team fields
$('.team_member').hide();
$('.show_for_' + type).show();
$('#' + type + '_fields').hide().removeClass('hidden').fadeIn(200);
$("#project_team").hide().removeClass('hidden').fadeIn(200);
},
'submit #newEntryForm': function (e) {
var error = false;
// Form Validation
if($('#type').val() == "none" || !$('#project_name').val()) {
Session.set('entryErrorMessage', 'Please ensure all required fields are completed.');
error = true;
}
if($('#notes').val().length > 400 || $('#project_description').val().length > 400) {
Session.set('entryErrorMessage', 'Please limit your notes and project description to 400 characters.');
error = true;
}
e.preventDefault();
if(!error) {
var entryData = utils.getFormValues("#newEntryForm");
if($(".motion-url").val() != "") entryData.url = $(".motion-url").val();
if($(".print-url").val() != "") entryData.url = $(".print-url").val();
if($(".web-url").val() != "") entryData.url = $(".web-url").val();
entryData.userId = Meteor.userId();
entryData.paid = false;
// Add any uploaded files
var files = Session.get('entry-files');
var fileArray = [];
if (files) fileArray = JSON.parse(Session.get('entry-files'));
entryData.files = fileArray;
Entries.insert(entryData);
$.pnotify({
text: 'Your entry was added.',
type: 'success',
icon: false,
addclass: "stack-bottomright",
stack: utils.pnotify_stack_bottomright,
sticker: false
});
Session.set('newEntry', false);
}
},
'click .filepicker-file': function(e) {
e.preventDefault();
var filepickerKey = Settings.findOne().filepickerKey;
if (!filepickerKey) return false;
filepicker.setKey(filepickerKey);
filepicker.pick(
function(FPFile){
var files = Session.get('entry-files');
var fileArray = [];
if (files) fileArray = JSON.parse(Session.get('entry-files'));
fileArray.push(FPFile);
Session.set('entry-files', JSON.stringify(fileArray));
console.log(FPFile.url);
}
);
},
'click .icon-remove-sign': function(e) {
var fileKey = this.key;
if(fileKey) {
var filepickerKey = Settings.findOne().filepickerKey;
if (!filepickerKey) return false;
filepicker.setKey(filepickerKey);
filepicker.remove(this, function() {
var files = Session.get('entry-files');
if (files) {
var fileArray = JSON.parse(Session.get('entry-files'));
fileArray = _.without(fileArray, _.findWhere(fileArray, {key: fileKey}));
Session.set('entry-files', JSON.stringify(fileArray));
}
}, function() { console.log("There was an error deleting the file"); });
}
}
});
Template.new_entry.entryErrorMessage = function() {
return Session.get('entryErrorMessage');
}
Template.new_entry.files = function() {
var files = Session.get('entry-files');
if (files) return JSON.parse(Session.get('entry-files'));
return [];
} | mit |
rajdeepv/nakal | lib/nakal.rb | 1329 | require 'rmagick'
require 'fileutils'
require 'yaml'
require 'pry'
require_relative "nakal/version"
require_relative 'nakal/base_screen'
require_relative 'nakal/android/screen'
require_relative 'nakal/ios/screen'
require_relative 'nakal/dsl'
module Nakal
class<<self
attr_accessor :device_name, :directory, :platform, :image_location, :default_crop_params
attr_accessor :diff_screens, :embed_screenshot, :timeout, :image_relative_dir, :fuzz, :config_location
def configure
yield self
end
def create_image_dir image_relative_dir
@image_relative_dir = image_relative_dir
@image_location = "#{@directory}/#{@device_name}/#{image_relative_dir}"
FileUtils.mkdir_p @image_location unless File.directory?(@image_location)
end
def load_config
@default_crop_params ||= YAML.load(File.open Nakal.config_location)
end
def set relative_location
create_image_dir relative_location
load_config
end
def current_platform
Nakal.const_get Nakal.platform.capitalize
end
end
end
Nakal.configure do |config|
config.device_name = "default_device"
config.directory = "baseline_images"
config.config_location = "./config/nakal.yml"
config.embed_screenshot = false
config.diff_screens = []
config.timeout = 30
config.fuzz = 10
end
| mit |
BaseCampOps/active_merchant | lib/active_merchant/billing/gateways/merchant_e_solutions.rb | 6947 | module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class MerchantESolutionsGateway < Gateway
include Empty
self.test_url = 'https://cert.merchante-solutions.com/mes-api/tridentApi'
self.live_url = 'https://api.merchante-solutions.com/mes-api/tridentApi'
# The countries the gateway supports merchants from as 2 digit ISO country codes
self.supported_countries = ['US']
# The card types supported by the payment gateway
self.supported_cardtypes = [:visa, :master, :american_express, :discover, :jcb]
# The homepage URL of the gateway
self.homepage_url = 'http://www.merchante-solutions.com/'
# The name of the gateway
self.display_name = 'Merchant e-Solutions'
def initialize(options = {})
requires!(options, :login, :password)
super
end
def authorize(money, creditcard_or_card_id, options = {})
post = {}
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
post[:moto_ecommerce_ind] = options[:moto_ecommerce_ind] if options.has_key?(:moto_ecommerce_ind)
add_invoice(post, options)
add_payment_source(post, creditcard_or_card_id, options)
add_address(post, options)
add_3dsecure_params(post, options)
commit('P', money, post)
end
def purchase(money, creditcard_or_card_id, options = {})
post = {}
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
post[:moto_ecommerce_ind] = options[:moto_ecommerce_ind] if options.has_key?(:moto_ecommerce_ind)
add_invoice(post, options)
add_payment_source(post, creditcard_or_card_id, options)
add_address(post, options)
add_3dsecure_params(post, options)
commit('D', money, post)
end
def capture(money, transaction_id, options = {})
post ={}
post[:transaction_id] = transaction_id
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
add_invoice(post, options)
add_3dsecure_params(post, options)
commit('S', money, post)
end
def store(creditcard, options = {})
post = {}
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
add_creditcard(post, creditcard, options)
commit('T', nil, post)
end
def unstore(card_id, options = {})
post = {}
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
post[:card_id] = card_id
commit('X', nil, post)
end
def refund(money, identification, options = {})
post = {}
post[:transaction_id] = identification
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
options.delete(:customer)
options.delete(:billing_address)
commit('U', money, options.merge(post))
end
def credit(money, creditcard_or_card_id, options = {})
post = {}
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
add_invoice(post, options)
add_payment_source(post, creditcard_or_card_id, options)
commit('C', money, post)
end
def void(transaction_id, options = {})
post = {}
post[:transaction_id] = transaction_id
post[:client_reference_number] = options[:customer] if options.has_key?(:customer)
options.delete(:customer)
options.delete(:billing_address)
commit('V', nil, options.merge(post))
end
def supports_scrubbing?
true
end
def scrub(transcript)
transcript.
gsub(%r((&?profile_key=)\w*(&?)), '\1[FILTERED]\2').
gsub(%r((&?card_number=)\d*(&?)), '\1[FILTERED]\2').
gsub(%r((&?cvv2=)\d*(&?)), '\1[FILTERED]\2')
end
private
def add_address(post, options)
if address = options[:billing_address] || options[:address]
post[:cardholder_street_address] = address[:address1].to_s.gsub(/[^\w.]/, '+')
post[:cardholder_zip] = address[:zip].to_s
end
end
def add_invoice(post, options)
if options.has_key? :order_id
order_id = options[:order_id].to_s.gsub(/[^\w.]/, '')
post[:invoice_number] = truncate(order_id, 17)
end
end
def add_payment_source(post, creditcard_or_card_id, options)
if creditcard_or_card_id.is_a?(String)
# using stored card
post[:card_id] = creditcard_or_card_id
post[:card_exp_date] = options[:expiration_date] if options[:expiration_date]
else
# card info is provided
add_creditcard(post, creditcard_or_card_id, options)
end
end
def add_creditcard(post, creditcard, options)
post[:card_number] = creditcard.number
post[:cvv2] = creditcard.verification_value if creditcard.verification_value?
post[:card_exp_date] = expdate(creditcard)
end
def add_3dsecure_params(post, options)
post[:xid] = options[:xid] unless empty?(options[:xid])
post[:cavv] = options[:cavv] unless empty?(options[:cavv])
post[:ucaf_collection_ind] = options[:ucaf_collection_ind] unless empty?(options[:ucaf_collection_ind])
post[:ucaf_auth_data] = options[:ucaf_auth_data] unless empty?(options[:ucaf_auth_data])
end
def parse(body)
results = {}
body.split(/&/).each do |pair|
key,val = pair.split(/=/)
results[key] = val
end
results
end
def commit(action, money, parameters)
url = test? ? self.test_url : self.live_url
parameters[:transaction_amount] = amount(money) if money unless action == 'V'
response = begin
parse( ssl_post(url, post_data(action,parameters)) )
rescue ActiveMerchant::ResponseError => e
{ "error_code" => "404", "auth_response_text" => e.to_s }
end
Response.new(response["error_code"] == "000", message_from(response), response,
:authorization => response["transaction_id"],
:test => test?,
:cvv_result => response["cvv2_result"],
:avs_result => { :code => response["avs_result"] }
)
end
def message_from(response)
if response["error_code"] == "000"
"This transaction has been approved"
else
response["auth_response_text"]
end
end
def post_data(action, parameters = {})
post = {}
post[:profile_id] = @options[:login]
post[:profile_key] = @options[:password]
post[:transaction_type] = action if action
request = post.merge(parameters).map {|key,value| "#{key}=#{CGI.escape(value.to_s)}"}.join("&")
request
end
end
end
end
| mit |
swinkelhofer/websites | AlisonThunderland/functions.js | 681 | function scrollUp()
{
iframe.window.scrollBy(0,-80);
}
function scrollDown()
{
iframe.window.scrollBy(0,80);
}
function loadNews()
{
document.all.iframe.setAttribute("src", "news.htm", "true");
}
function loadAlison()
{
document.all.iframe.setAttribute("src", "alison.htm", "true");
}
function loadContact()
{
document.all.iframe.setAttribute("src", "contact.htm", "true");
}
function loadNewsletter()
{
document.all.iframe.setAttribute("src", "letter.php", "true");
}
function loadPress()
{
document.all.iframe.setAttribute("src", "press.htm", "true");
}
function loadImpressum()
{
document.all.iframe.setAttribute("src", "impressum.htm", "true");
} | mit |
davidbgk/comprendre-javascript | 07-le-call/03.js | 1003 | /* Une fois les concepts `apply`, `this` et `arguments`
compris, on peut s'amuser à les combiner pour faire des
fonctions génériques. */
var GoodHunter = { bringBack: "Mushrooms" };
var BadHunter = { bringBack: "Nothing" };
function gotMushrooms(people) {
return people.bringBack === "Mushrooms";
}
console.log(gotMushrooms(GoodHunter)); // => true
console.log(gotMushrooms(BadHunter)); // => false
/* Jusqu'ici tout va bien, maitenant trouvons la
fonction générique permettant de retourner le contraire
d'une fonction existante. */
function not(originalFunc) {
return function () {
return !originalFunc.apply(this, arguments);
};
}
/* On crée dynamiquement une nouvelle fonction. */
var dontHaveMushrooms = not(gotMushrooms);
/* Qui devient directement utilisable. */
console.log(dontHaveMushrooms(GoodHunter)); // => false
console.log(dontHaveMushrooms(BadHunter)); // => true
/* Cela permet de réduire la taille du code sur des
exemples plus complexes/pertinents. */
| mit |
SungwooNam/sketchup-motion | sketchup-developer-tools unit tests/TEST_MOTION_ACTION.rb | 5808 | require 'test/unit'
require 'motion.rb'
include Motion
class TEST_MOTION_ACTION < Test::Unit::TestCase
class AlwaysArrivedAction < Motion::Action
def arrived?() true; end
def tick( sec = 1.0 ) fire_arrived_fn; end
end
def test_should_call_all_the_added_fn_when_arrived
action = AlwaysArrivedAction.new
trace = []
action.when_arrived << lambda { |a| trace << 1 }
action.when_arrived << lambda { |a| trace << 2 }
action.tick
assert_equal( [1,2], trace )
end
end
=begin
def test_796127_point_to_latlong
skp = Sketchup.active_model
skp.entities.clear!
point = Geom::Point3d.new([10, 10, 10])
lat_long = skp.point_to_latlong(point)
fail_msg = 'Model.point_to_latlong did not return a Geom::LatLong ' +
'object. See bug report <a href="http://b/issue?id=796127">' +
'796127</a>.'
assert_equal('Geom::LatLong', lat_long.class.to_s, fail_msg)
end
def test_796127_latlong_to_point
skp = Sketchup.active_model
skp.entities.clear!
lat_long = Geom::LatLong.new([50, 100])
point = skp.latlong_to_point(lat_long)
fail_msg = 'Model.latlong_to_point() did not return a Geom::Point3d ' +
'object.'
assert_equal('Geom::Point3d', point.class.to_s, fail_msg)
end
end
require 'minitest/spec'
require 'minitest/mock'
require 'minitest/autorun'
load File.expand_path('Motion.rb', File.dirname(__FILE__))
#require './motion.rb'
include Motion
describe Motion::Action do
class AlwaysArrivedAction < Motion::Action
def arrived?() true; end
def tick( sec = 1.0 ) fire_arrived_fn; end
end
it "should call all the added fn when arrived" do
action = AlwaysArrivedAction.new
trace = []
action.when_arrived << lambda { |a| trace << 1 }
action.when_arrived << lambda { |a| trace << 2 }
action.tick
trace.must_equal [1,2]
end
end
describe Motion::Translation do
it "can be created but not arrived yet" do
t = Motion::Translation.new nil, nil, 1.0
t.arrived?.must_equal false
end
it "should hold target position" do
mock_target = MiniTest::Mock.new
mock_target.expect :x, 1.0
mock_target.expect :y, 0.0
mock_target.expect :z, 0.0
t = Motion::Translation.new nil, mock_target, 1.0
t.target.x.must_equal 1.0
t.target.y.must_equal 0.0
t.target.z.must_equal 0.0
end
end
describe Motion::PairInArray do
it "should return index in pairs" do
a = PairInArray.new
a.add( 0, 1 )
a.add( 2, 3 )
a.add( 1, 2 )
a.length.must_equal 3
i,j = a.find( 1 )
i.must_equal 0
j.must_equal 1
i,j = a.find(2)
i.must_equal 1
j.must_equal 0
i,j = a.find(4)
i.must_equal nil
j.must_equal nil
end
it "should delete given index" do
a = PairInArray.new
a.add( 0, 1 )
a.add( 2, 3 )
a.add( 1, 2 )
i,j = a.find( 1 )
i.must_equal 0
a.delete_at( 0 )
i,j = a.find(1)
i.must_equal 1
a.length.must_equal 2
end
it "should get pair in index" do
a = PairInArray.new
a.add( 0, 1 )
a.add( 2, 3 )
a.add( 1, 2 )
i,j = a[1]
i.must_equal 2
j.must_equal 3
end
it "should be able to make PariInArray easily" do
pairs = PairInArray.new
edges = [ Edge.new(0,1), Edge.new(2,3), Edge.new(1,2) ]
edges.each { |e| pairs.add( e.start, e.end ) }
pairs.length.must_equal 3
end
it "should be able to pop front" do
pairs = PairInArray.new
pairs.add( 0, 1 )
pairs.add( 2, 3 )
s,e = pairs.pop_front
s.must_equal 0
e.must_equal 1
pairs.length.must_equal 1
end
it "should be able to return values in array" do
pairs = PairInArray.new
pairs.add( 0, 1 )
e = pairs[0]
e[0].must_equal 0
e[1].must_equal 1
end
end
describe Motion::Edge do
it "should return value at start with index 0 and end with 1" do
e = Edge.new( "START", "END" )
e[0].must_equal e.start
e[1].must_equal e.end
e[-1].must_equal e.end
end
it "should raise exception when out of bound index used" do
e = Edge.new( "START", "END" )
proc { e[2] }.must_raise RuntimeError
end
end
describe Motion::DoubleLinkedList do
it "should add values to head" do
list = DoubleLinkedList.new()
list.add_head Vertice.new( 3 )
list.add_head Vertice.new( 2 )
list.add_head Vertice.new( 1 )
a = list.map{ |e| e.element }.to_a
a.must_equal [1,2,3]
end
it "should add values to tail" do
list = DoubleLinkedList.new()
list.add_tail Vertice.new( 3 )
list.add_tail Vertice.new( 2 )
list.add_tail Vertice.new( 1 )
a = list.map{ |e| e.element }.to_a
a.must_equal [3,2,1]
end
it "should add values to head and tail" do
list = DoubleLinkedList.new()
list.add_tail Vertice.new( 3 )
list.add_head Vertice.new( 2 )
list.add_head Vertice.new( 1 )
a = list.map{ |e| e.element }.to_a
a.must_equal [1,2,3]
end
it "can have no element" do
list = DoubleLinkedList.new()
a = list.map{ |e| e.element }.to_a
a.must_equal []
end
end
describe Motion::Graph do
it "should find path in order" do
path = Graph::find_path( [ Edge.new(0,1), Edge.new(2,3), Edge.new(1,2) ] )
path.map { |v| v.element }.to_a.must_equal [0,1,2,3]
end
it "should find path in reverse order" do
path = Graph::find_path( [ Edge.new(0,1), Edge.new(2,3), Edge.new(2,0) ] )
path.map { |v| v.element }.to_a.must_equal [3,2,0,1]
end
it "should find path in order and reverse" do
path = Graph::find_path( [ Edge.new(2,3), Edge.new(0,1), Edge.new(4,5), Edge.new(3,4), Edge.new(1,2) ] )
path.map { |v| v.element }.to_a.must_equal [0,1,2,3,4,5]
end
end
module Sketchup
class Model
def dumpr
return true
end
end
end
class SketchupConsoleOutput
def puts s
print s.to_s + "\n"
end
def write s
print s
end
def flush
#nop
# The testrunner expects to be able to call this method on the supplied io object.
end
end
=end
| mit |
bitjson/bitcore | packages/bitcore-client/src/providers/tx-provider/btc/index.ts | 1419 | export class BTCTxProvder {
lib = require('bitcore-lib');
create({ recipients, utxos, change, fee }) {
let tx = new this.lib.Transaction().from(utxos).fee(Number(fee));
for (const recipient of recipients) {
tx.to(recipient.address, recipient.amount);
}
if (change) {
tx.change(change);
}
return tx;
}
sign({ tx, keys, utxos }) {
let bitcoreTx = new this.lib.Transaction(tx);
let applicableUtxos = this.getRelatedUtxos({
outputs: bitcoreTx.inputs,
utxos
});
let newTx = new this.lib.Transaction()
.from(applicableUtxos)
.to(this.getOutputsFromTx({ tx: bitcoreTx }));
const privKeys = keys.map(key => key.privKey.toString('hex'));
return newTx.sign(privKeys);
}
getRelatedUtxos({ outputs, utxos }) {
let txids = outputs.map(output => output.toObject().prevTxId);
let applicableUtxos = utxos.filter(utxo => txids.includes(utxo.txid));
return applicableUtxos;
}
getOutputsFromTx({ tx }) {
return tx.outputs.map(({ script, satoshis }) => {
let address = script;
return { address, satoshis };
});
}
getSigningAddresses({ tx, utxos }) {
let bitcoreTx = new this.lib.Transaction(tx);
let applicableUtxos = this.getRelatedUtxos({
outputs: bitcoreTx.inputs,
utxos
});
return applicableUtxos.map(utxo => utxo.address);
}
}
export default new BTCTxProvder();
| mit |
ismailakbudak/layered-architecture | Container/SITE.cs | 1448 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Container
{
using System;
using System.Collections.Generic;
public partial class SITE
{
public SITE()
{
this.COMMENTS = new HashSet<COMMENTS>();
this.IMAGE = new HashSet<IMAGE>();
this.VOTE = new HashSet<VOTE>();
}
public int ID { get; set; }
public Nullable<int> UserID { get; set; }
public Nullable<int> SubCategoryID { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string InsertDate { get; set; }
public Nullable<int> Status { get; set; }
public Nullable<int> Active { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
public virtual ICollection<COMMENTS> COMMENTS { get; set; }
public virtual ICollection<IMAGE> IMAGE { get; set; }
public virtual USERS USERS { get; set; }
public virtual ICollection<VOTE> VOTE { get; set; }
}
}
| mit |
creatubbles/ctb-mcmod | src/main/java/com/creatubbles/repack/endercore/client/gui/GuiScreenBase.java | 6757 | package com.creatubbles.repack.endercore.client.gui;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.RenderHelper;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import com.creatubbles.repack.endercore.api.client.gui.IGuiScreen;
import com.creatubbles.repack.endercore.client.gui.ToolTipManager.ToolTipRenderer;
import com.creatubbles.repack.endercore.client.gui.widget.GhostSlot;
import com.creatubbles.repack.endercore.client.gui.widget.GuiToolTip;
public abstract class GuiScreenBase extends GuiScreen implements ToolTipRenderer, IGuiScreen {
protected ToolTipManager ttMan = new ToolTipManager();
/** The X size of the inventory window in pixels. */
protected int xSize = 176;
/** The Y size of the inventory window in pixels. */
protected int ySize = 166;
/**
* Starting X position for the Gui. Inconsistent use for Gui backgrounds.
*/
protected int guiLeft;
/**
* Starting Y position for the Gui. Inconsistent use for Gui backgrounds.
*/
protected int guiTop;
protected boolean drawButtons = true;
protected GuiScreenBase() {}
protected GuiScreenBase(int xSize, int ySize) {
this.xSize = xSize;
this.ySize = ySize;
}
@Override
public void addToolTip(GuiToolTip toolTip) {
ttMan.addToolTip(toolTip);
}
@Override
public boolean removeToolTip(GuiToolTip toolTip) {
return ttMan.removeToolTip(toolTip);
}
@Override
public void initGui() {
super.initGui();
guiLeft = (width - xSize) / 2;
guiTop = (height - ySize) / 2;
}
@Override
public void drawScreen(int par1, int par2, float par3) {
drawDefaultBackground();
drawBackgroundLayer(par3, par1, par2);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
if (drawButtons) {
RenderHelper.enableGUIStandardItemLighting();
super.drawScreen(par1, par2, par3);
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glPushMatrix();
GL11.glTranslatef(guiLeft, guiTop, 0.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
drawForegroundLayer(par1, par2);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
}
protected abstract void drawBackgroundLayer(float par3, int par1, int par2);
protected final void drawForegroundLayer(int mouseX, int mouseY) {
drawForegroundImpl(mouseX, mouseY);
ttMan.drawTooltips(this, mouseX, mouseY);
}
protected void drawForegroundImpl(int mouseX, int mouseY) {}
@SuppressWarnings("rawtypes")
@Override
public void drawHoveringText(List par1List, int par2, int par3, FontRenderer font) {
if (!par1List.isEmpty()) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT);
GL11.glPushAttrib(GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int k = 0;
Iterator iterator = par1List.iterator();
while (iterator.hasNext()) {
String s = (String) iterator.next();
int l = font.getStringWidth(s);
if (l > k) {
k = l;
}
}
int i1 = par2 + 12;
int j1 = par3 - 12;
int k1 = 8;
if (par1List.size() > 1) {
k1 += 2 + (par1List.size() - 1) * 10;
}
if (i1 + k > width) {
i1 -= 28 + k;
}
if (j1 + k1 + 6 > height) {
j1 = height - k1 - 6;
}
zLevel = 300.0F;
int l1 = -267386864;
drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1);
drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1);
int i2 = 1347420415;
int j2 = (i2 & 16711422) >> 1 | i2 & -16777216;
drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2);
drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2);
for (int k2 = 0; k2 < par1List.size(); ++k2) {
String s1 = (String) par1List.get(k2);
font.drawStringWithShadow(s1, i1, j1, -1);
if (k2 == 0) {
j1 += 2;
}
j1 += 10;
}
zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glPopAttrib();
GL11.glPopAttrib();
}
}
@Override
public int getGuiLeft() {
return guiLeft;
}
@Override
public int getGuiTop() {
return guiTop;
}
@Override
public int getXSize() {
return xSize;
}
@Override
public int getYSize() {
return xSize;
}
@Override
public FontRenderer getFontRenderer() {
return Minecraft.getMinecraft().fontRendererObj;
}
@Override
public void addButton(GuiButton button) {
if (!buttonList.contains(button)) {
buttonList.add(button);
}
}
@Override
public void removeButton(GuiButton button) {
buttonList.remove(button);
}
@Override
public void doActionPerformed(GuiButton guiButton) throws IOException {
actionPerformed(guiButton);
}
@Override
public int getOverlayOffsetX() {
return 0;
}
@Override
public List<GhostSlot> getGhostSlots() {
return null;
}
}
| mit |
artisin/js-library-setup-guide | __scripts__/setup/generate-files/nvmrc.generate.js | 536 | const fs = require('fs-extra');
const path = require('path');
/**
* Configs the .nvmrc file
*/
const config = function ({dir, nvmrc}) {
let data = fs.readFileSync(path.resolve(__dirname, './template/.nvmrc'));
if (data) {
data = data.toString();
data = data.replace(/<VERSION>/g, nvmrc).replace(/"|'/g, '');
//write out file
fs.writeFileSync(`${dir}.nvmrc`, data);
}
};
/**
* Example input
*/
// config({
// dir: './__scripts__/setup/__tests__/',
// nvmrc: '8.5.0'
// });
module.exports = config;
| mit |
yeahsmaggy/Slim-Tour-CMS | public/css/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-he.min.js | 930 | /*! jQuery UI - v1.10.4 - 2018-06-10
* http://jqueryui.com
* Copyright jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.he={closeText:"סגור",prevText:"<הקודם",nextText:"הבא>",currentText:"היום",monthNames:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],monthNamesShort:["ינו","פבר","מרץ","אפר","מאי","יוני","יולי","אוג","ספט","אוק","נוב","דצמ"],dayNames:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],dayNamesShort:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],dayNamesMin:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.he)}); | mit |
kazimanzurrashid/textuml-dotnet | source/TextUml/Infrastructure/Membership/AppIdentityAuthenticationManager.cs | 1572 | namespace TextUml.Infrastructure
{
using System;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
[CLSCompliant(false)]
public class AppIdentityAuthenticationManager : IdentityAuthenticationManager
{
private readonly AppIdentityStoreManager storeManager;
public AppIdentityAuthenticationManager(AppIdentityStoreManager storeManager)
: base(storeManager)
{
this.storeManager = storeManager;
}
public async Task<bool> CreateAndSignInExternalUser(
HttpContextBase context,
string logOnProvider,
IUser user,
string role,
bool persist)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
var identity = await GetExternalIdentity(context);
if (!VerifyExternalIdentity(identity, logOnProvider))
{
return false;
}
var providerKey = identity.FindFirstValue(
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");
if (!(await storeManager.CreateExternalUser(
user,
logOnProvider,
providerKey,
role)))
{
return false;
}
await SignIn(context, user.Id, identity.Claims, persist);
return true;
}
}
} | mit |
bcvsolutions/CzechIdMng | Realization/frontend/czechidm-core/src/content/notification/email/Emails.js | 822 | import React from 'react';
import * as Basic from '../../../components/basic';
import { EmailManager } from '../../../redux';
import EmailTable from './EmailTable';
/**
* List of email in audit log.
*
* @author Radek Tomiška
*/
export default class Emails extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.emailManager = new EmailManager();
}
getContentKey() {
return 'content.emails';
}
getNavigationKey() {
return 'notification-emails';
}
render() {
return (
<Basic.Div>
{ this.renderPageHeader() }
<Basic.Panel>
<EmailTable uiKey="email_table" emailManager={ this.emailManager } filterOpened/>
</Basic.Panel>
</Basic.Div>
);
}
}
Emails.propTypes = {
};
Emails.defaultProps = {
};
| mit |
reedcwilson/programming-fundamentals | lessons/6/6.py | 1074 | #!/usr/bin/env python
#==============================================================================#
#-------------------------------- Introduction --------------------------------#
#==============================================================================#
# OUTLINE:
# questions . . .
# review
print '________ ______ '
print '___ __ \______________ /__'
print '__ /_/ / __ \ ___/_ //_/'
print '_ _, _// /_/ / /__ _ ,< '
print '/_/ |_| \____/\___/ /_/|_| '
print '________ '
print '___ __ \_____ _____________________'
print '__ /_/ / __ `/__ __ \ _ \_ ___/'
print '_ ____// /_/ /__ /_/ / __/ / '
print '/_/ \__,_/ _ .___/\___//_/ '
print ' /_/ '
print '________ _____ '
print '__ ___/________(_)__________________________________'
print '_____ \_ ___/_ /__ ___/_ ___/ __ \_ ___/_ ___/'
print '____/ // /__ _ / _(__ )_(__ )/ /_/ / / _(__ ) '
print '/____/ \___/ /_/ /____/ /____/ \____//_/ /____/ '
| mit |
Topolev/TimeCurrentCharacteristic | src/app/draw-tripping-characteristics/coordinate-panel/area-builder.ts | 701 | import {Area, AreaTemplate} from "./area-template";
export class BuilderArea {
public buildAreaByTemplate(areaTemplate: AreaTemplate): Area {
var area: Area = new Area();
area.xEnd = null;
area.xStart = null;
area.areaTemplate = areaTemplate;
area.type = areaTemplate.type;
if (area.type == 0){
area.points = [];
area.pointsTemplate = null;
}
if (area.type == 1 || area.type == 2) {
area.fn = areaTemplate.fn;
if (areaTemplate.variableDescriptions) {
area.variables = [];
for (let variable of areaTemplate.variableDescriptions) {
area.variables[variable.label] = null;
}
}
}
return area;
}
}
| mit |
jrowberg/keyglove | docs/arduino/html/search/classes_1.js | 108 | var searchData=
[
['iwrap_5fpairing_5ft',['iwrap_pairing_t',['../structiwrap__pairing__t.html',1,'']]]
];
| mit |
olivif/bookman | lib/goodreadsApi.js | 4105 | var api = {};
const request = require('request');
const parseString = require('xml2js').parseString;
const apiBase = 'https://www.goodreads.com';
// https://www.goodreads.com/shelf/list.xml
// key: Developer key (required).
// user_id: Goodreads user id (required)
// page: 1-N (default 1)
api.getShelves = function (userId, callback) {
// TOOD handle multiple pages?
var params = {
key: process.env.GOODREADS_KEY,
user_id: userId,
page: 1
};
var url = apiBase + '/shelf/list.xml';
var requestOptions = { url: url, qs: params };
request(requestOptions, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
var unpackedResult = result.GoodreadsResponse.shelves[0].user_shelf;
if (unpackedResult === null || unpackedResult === undefined) {
console.log('got undefined for shelves');
callback([]);
} else {
callback(unpackedResult);
console.log(unpackedResult.length);
}
});
}
});
};
// https://www.goodreads.com/review/list?v=2
// v: 2
// id: Goodreads id of the user
// shelf: read, currently-reading, to-read, etc. (optional)
// sort: title, author, cover, rating, year_pub, date_pub, date_pub_edition, date_started,
// date_read, date_updated, date_added, recommender, avg_rating, num_ratings, review, read_count,
// votes, random, comments, notes, isbn, isbn13, asin, num_pages, format, position, shelves,
// owned, date_purchased, purchase_location, condition (optional)
// search[query]: query text to match against member's books (optional)
// order: a, d (optional)
// page: 1-N (optional)
// per_page: 1-200 (optional)
// key: Developer key (required).
api.getBooksForShelf = function (userId, shelfName, page, perPage, callback) {
// TOOD handle multiple pages?
var params = {
v: 2,
id: userId,
shelf: shelfName,
sort: 'date_read',
order: 'd',
page: page,
per_page: perPage,
key: process.env.GOODREADS_KEY,
};
var url = apiBase + '/review/list.xml';
var requestOptions = { url: url, qs: params };
request(requestOptions, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
var unpackedResult = result.GoodreadsResponse.reviews[0].review;
if (unpackedResult === null || unpackedResult === undefined) {
console.log('got undefined for books');
callback([]);
} else {
callback(unpackedResult);
console.log(unpackedResult.length);
}
});
}
});
};
// Get an xml response with a paginated list of an authors books.
// URL: https://www.goodreads.com/author/list.xml (sample url)
// HTTP method: GET
// Parameters:
// •key: Developer key (required).
// •id: Goodreads Author id (required)
// •page: 1-N (default 1)
api.getAuthorBooks = function (authorId, page, callback) {
var params = {
key: process.env.GOODREADS_KEY,
id: authorId,
page: page,
};
var url = apiBase + '/author/list.xml';
var requestOptions = { url: url, qs: params };
request(requestOptions, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
var unpackedResult = result.GoodreadsResponse.author[0].books[0].book;
if (unpackedResult === null || unpackedResult === undefined) {
console.log('got undefined for author books');
callback([]);
} else {
callback(unpackedResult);
console.log(unpackedResult);
}
});
}
});
};
module.exports = api; | mit |
sholev/SoftUni | OpenCourses/JavaWebDevelopment/Project/ThemBooks/src/main/java/bg/softuni/library/dao/user/RolesDao.java | 2171 | package bg.softuni.library.dao.user;
import java.util.List;
import java.util.ArrayList;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import bg.softuni.library.entity.user.Role;
import bg.softuni.library.interfaces.RolesStorage;
@Repository
public class RolesDao implements RolesStorage {
@Autowired
SessionFactory sessionFactory;
@Override
public List<String> getRoles() {
List<String> result = new ArrayList<>();
Criteria criteria = sessionFactory
.openSession()
.createCriteria(Role.class);
for (Object role : criteria.list()) {
Role userRole = (Role)role;
result.add(userRole.getRole());
}
return result;
}
@Override
public List<String> getRoles(Long id) {
List<String> result = new ArrayList<>();
Criteria criteria = sessionFactory
.openSession()
.createCriteria(Role.class)
.add(Restrictions.eq("userId", id));
for (Object role : criteria.list()) {
Role userRole = (Role)role;
result.add(userRole.getRole());
}
return result;
}
@Override
public boolean addRoles(Long userId, String... roles) {
Long lastId = getMaxId();
Transaction transaction = null;
try (Session session = this.sessionFactory.openSession();) {
transaction = session.beginTransaction();
for(String role : roles) {
lastId++;
Role newRole = new Role(lastId, userId, role);
session.save(newRole);
}
transaction.commit();
} catch (HibernateException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
return false;
}
return true;
}
private Long getMaxId() {
Object lastEntry = sessionFactory
.openSession()
.createCriteria(Role.class)
.addOrder(Order.desc("id"))
.setMaxResults(1)
.uniqueResult();
return ((Role)lastEntry).getId();
}
}
| mit |
didiercrunch/vulture | stats_test.go | 1489 | package main
import (
"testing"
)
func TestNewStats(t *testing.T) {
s := NewStatAggregator()
if s.n != 0 ||
s.sum != 0 ||
s.sumOfTheSquares != 0 ||
len(s.histogram) != initialLength ||
s.min != veryBig ||
s.max != verySmall {
t.Fail()
}
}
func TestAddStatsBasic(t *testing.T) {
numbers := []float64{-1, 1, 20, 3}
c := make(chan float64)
o := make(chan *Stats)
s := NewStatAggregator()
go s.AddStats(c, o)
for _, n := range numbers {
c <- n
}
close(c)
<-o
if s.n != 4. || s.min != -1. || s.max != 20. || s.sum != 23. || s.sumOfTheSquares != 411. {
t.Error(">>>", s.max, s.min)
}
}
func TestGetFinalStats(t *testing.T) {
s := NewStatAggregator()
s.sumOfTheSquares = 5000
s.max = 900
s.min = -900
s.sum = 200
s.n = 10
stats := s.getFinalStats()
if stats.Mean != 20. {
t.Fail()
}
if stats.Var != 100. {
t.Fail()
}
if stats.Std != 10. {
t.Fail()
}
if stats.Min != -900 {
t.Fail()
}
if stats.Max != 900 {
t.Fail()
}
if stats.N != 10 {
t.Fail()
}
}
func TestFindSuitableBinForDatum(t *testing.T) {
stats := new(HistogramMaker)
if bin := stats.findSuitableBinForDatum(-4, 1, -3.2); bin != 0 {
t.Error("wrong bin: ", bin)
}
if bin := stats.findSuitableBinForDatum(-4, 1, -2.2); bin != 1 {
t.Error("wrong bin: ", bin)
}
if bin := stats.findSuitableBinForDatum(-4, 1, 10.1); bin != 14 {
t.Error("wrong bin: ", bin)
}
if bin := stats.findSuitableBinForDatum(1, 50, 1); bin != 0 {
t.Error("wrong bin: ", bin)
}
}
| mit |
nico01f/z-pec | ZimbraServer/src/java/com/zimbra/cs/account/ldap/LdapProvisioning.java | 402683 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.account.ldap;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.AccountBy;
import com.zimbra.common.account.Key.DistributionListBy;
import com.zimbra.common.account.Key.GranteeBy;
import com.zimbra.common.account.Key.UCServiceBy;
import com.zimbra.common.account.ProvisioningConstants;
import com.zimbra.common.localconfig.LC;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.service.ServiceException.Argument;
import com.zimbra.common.soap.Element;
import com.zimbra.common.util.Constants;
import com.zimbra.common.util.DateUtil;
import com.zimbra.common.util.EmailUtil;
import com.zimbra.common.util.L10nUtil;
import com.zimbra.common.util.Log;
import com.zimbra.common.util.LogFactory;
import com.zimbra.common.util.SetUtil;
import com.zimbra.common.util.StringUtil;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.AccessManager;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.AccountServiceException;
import com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException;
import com.zimbra.cs.account.Alias;
import com.zimbra.cs.account.AliasedEntry;
import com.zimbra.cs.account.AttributeClass;
import com.zimbra.cs.account.AttributeInfo;
import com.zimbra.cs.account.AttributeManager;
import com.zimbra.cs.account.CalendarResource;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Cos;
import com.zimbra.cs.account.DataSource;
import com.zimbra.cs.account.DistributionList;
import com.zimbra.cs.account.Domain;
import com.zimbra.cs.account.DynamicGroup;
import com.zimbra.cs.account.Entry;
import com.zimbra.cs.account.EntryCacheDataKey;
import com.zimbra.cs.account.GalContact;
import com.zimbra.cs.account.GlobalGrant;
import com.zimbra.cs.account.Group;
import com.zimbra.cs.account.GroupedEntry;
import com.zimbra.cs.account.GuestAccount;
import com.zimbra.cs.account.IDNUtil;
import com.zimbra.cs.account.Identity;
import com.zimbra.cs.account.NamedEntry;
import com.zimbra.cs.account.PreAuthKey;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.ProvisioningExt;
import com.zimbra.cs.account.SearchAccountsOptions;
import com.zimbra.cs.account.UCService;
import com.zimbra.cs.account.ProvisioningExt.PostCreateAccountListener;
import com.zimbra.cs.account.SearchAccountsOptions.IncludeType;
import com.zimbra.cs.account.SearchDirectoryOptions;
import com.zimbra.cs.account.SearchDirectoryOptions.MakeObjectOpt;
import com.zimbra.cs.account.SearchDirectoryOptions.ObjectType;
import com.zimbra.cs.account.SearchDirectoryOptions.SortOpt;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.account.ShareLocator;
import com.zimbra.cs.account.Signature;
import com.zimbra.cs.account.XMPPComponent;
import com.zimbra.cs.account.Zimlet;
import com.zimbra.cs.account.accesscontrol.GranteeType;
import com.zimbra.cs.account.accesscontrol.PermissionCache;
import com.zimbra.cs.account.accesscontrol.Right;
import com.zimbra.cs.account.accesscontrol.RightCommand;
import com.zimbra.cs.account.accesscontrol.RightCommand.EffectiveRights;
import com.zimbra.cs.account.accesscontrol.RightModifier;
import com.zimbra.cs.account.accesscontrol.TargetType;
import com.zimbra.cs.account.auth.AuthContext;
import com.zimbra.cs.account.auth.AuthMechanism;
import com.zimbra.cs.account.auth.AuthMechanism.AuthMech;
import com.zimbra.cs.account.auth.PasswordUtil;
import com.zimbra.cs.account.cache.DomainCache;
import com.zimbra.cs.account.cache.IAccountCache;
import com.zimbra.cs.account.cache.IDomainCache;
import com.zimbra.cs.account.cache.IMimeTypeCache;
import com.zimbra.cs.account.cache.INamedEntryCache;
import com.zimbra.cs.account.cache.DomainCache.GetFromDomainCacheOption;
import com.zimbra.cs.account.callback.CallbackContext;
import com.zimbra.cs.account.callback.CallbackContext.DataKey;
import com.zimbra.cs.account.gal.GalNamedFilter;
import com.zimbra.cs.account.gal.GalOp;
import com.zimbra.cs.account.gal.GalParams;
import com.zimbra.cs.account.gal.GalUtil;
import com.zimbra.cs.account.krb5.Krb5Principal;
import com.zimbra.cs.account.ldap.entry.LdapAccount;
import com.zimbra.cs.account.ldap.entry.LdapAlias;
import com.zimbra.cs.account.ldap.entry.LdapCalendarResource;
import com.zimbra.cs.account.ldap.entry.LdapConfig;
import com.zimbra.cs.account.ldap.entry.LdapCos;
import com.zimbra.cs.account.ldap.entry.LdapDataSource;
import com.zimbra.cs.account.ldap.entry.LdapDistributionList;
import com.zimbra.cs.account.ldap.entry.LdapDomain;
import com.zimbra.cs.account.ldap.entry.LdapDynamicGroup;
import com.zimbra.cs.account.ldap.entry.LdapEntry;
import com.zimbra.cs.account.ldap.entry.LdapGlobalGrant;
import com.zimbra.cs.account.ldap.entry.LdapIdentity;
import com.zimbra.cs.account.ldap.entry.LdapMimeType;
import com.zimbra.cs.account.ldap.entry.LdapServer;
import com.zimbra.cs.account.ldap.entry.LdapShareLocator;
import com.zimbra.cs.account.ldap.entry.LdapSignature;
import com.zimbra.cs.account.ldap.entry.LdapUCService;
import com.zimbra.cs.account.ldap.entry.LdapXMPPComponent;
import com.zimbra.cs.account.ldap.entry.LdapZimlet;
import com.zimbra.cs.account.names.NameUtil;
import com.zimbra.cs.account.names.NameUtil.EmailAddress;
import com.zimbra.cs.gal.GalSearchConfig;
import com.zimbra.cs.gal.GalSearchControl;
import com.zimbra.cs.gal.GalSearchParams;
import com.zimbra.cs.gal.GalSearchResultCallback;
import com.zimbra.cs.gal.GalSyncToken;
import com.zimbra.cs.httpclient.URLUtil;
import com.zimbra.cs.ldap.IAttributes;
import com.zimbra.cs.ldap.IAttributes.CheckBinary;
import com.zimbra.cs.ldap.LdapClient;
import com.zimbra.cs.ldap.LdapConstants;
import com.zimbra.cs.ldap.LdapException;
import com.zimbra.cs.ldap.LdapException.LdapContextNotEmptyException;
import com.zimbra.cs.ldap.LdapException.LdapEntryAlreadyExistException;
import com.zimbra.cs.ldap.LdapException.LdapEntryNotFoundException;
import com.zimbra.cs.ldap.LdapException.LdapInvalidAttrNameException;
import com.zimbra.cs.ldap.LdapException.LdapInvalidAttrValueException;
import com.zimbra.cs.ldap.LdapException.LdapInvalidSearchFilterException;
import com.zimbra.cs.ldap.LdapException.LdapMultipleEntriesMatchedException;
import com.zimbra.cs.ldap.LdapException.LdapSizeLimitExceededException;
import com.zimbra.cs.ldap.LdapServerConfig.ExternalLdapConfig;
import com.zimbra.cs.ldap.LdapServerType;
import com.zimbra.cs.ldap.LdapTODO.TODO;
import com.zimbra.cs.ldap.LdapUsage;
import com.zimbra.cs.ldap.LdapUtil;
import com.zimbra.cs.ldap.SearchLdapOptions;
import com.zimbra.cs.ldap.SearchLdapOptions.SearchLdapVisitor;
import com.zimbra.cs.ldap.SearchLdapOptions.StopIteratingException;
import com.zimbra.cs.ldap.ZAttributes;
import com.zimbra.cs.ldap.ZLdapContext;
import com.zimbra.cs.ldap.ZLdapFilter;
import com.zimbra.cs.ldap.ZLdapFilterFactory;
import com.zimbra.cs.ldap.ZLdapFilterFactory.FilterId;
import com.zimbra.cs.ldap.ZLdapSchema;
import com.zimbra.cs.ldap.ZMutableEntry;
import com.zimbra.cs.ldap.ZSearchControls;
import com.zimbra.cs.ldap.ZSearchResultEntry;
import com.zimbra.cs.ldap.ZSearchResultEnumeration;
import com.zimbra.cs.ldap.ZSearchScope;
import com.zimbra.cs.ldap.unboundid.InMemoryLdapServer;
import com.zimbra.cs.mime.MimeTypeInfo;
import com.zimbra.cs.util.Zimbra;
import com.zimbra.cs.zimlet.ZimletException;
import com.zimbra.cs.zimlet.ZimletUtil;
import com.zimbra.soap.admin.type.CacheEntryType;
import com.zimbra.soap.admin.type.CountObjectsType;
import com.zimbra.soap.admin.type.DataSourceType;
import com.zimbra.soap.type.AutoProvPrincipalBy;
import com.zimbra.soap.type.GalSearchType;
import com.zimbra.soap.type.TargetBy;
/**
* LDAP implementation of {@link Provisioning}.
*
* @since Sep 23, 2004
* @author schemers
*/
public class LdapProvisioning extends LdapProv {
private static final Log mLog = LogFactory.getLog(LdapProvisioning.class);
private static final String[] sInvalidAccountCreateModifyAttrs = {
Provisioning.A_uid,
Provisioning.A_zimbraMailAlias,
Provisioning.A_zimbraMailDeliveryAddress,
};
private boolean useCache;
private LdapCache cache;
private IAccountCache accountCache;
private INamedEntryCache<LdapCos> cosCache;
private IDomainCache domainCache;
private INamedEntryCache<Group> groupCache;
private IMimeTypeCache mimeTypeCache;
private INamedEntryCache<Server> serverCache;
private INamedEntryCache<UCService> ucServiceCache;
private INamedEntryCache<ShareLocator> shareLocatorCache;
private INamedEntryCache<XMPPComponent> xmppComponentCache;
private INamedEntryCache<LdapZimlet> zimletCache;
private LdapConfig cachedGlobalConfig = null;
private GlobalGrant cachedGlobalGrant = null;
private static final Random sPoolRandom = new Random();
private Groups allDLs; // email addresses of all distribution lists on the system
private ZLdapFilterFactory filterFactory;
private String[] BASIC_DL_ATTRS;
private String[] BASIC_DYNAMIC_GROUP_ATTRS;
private String[] BASIC_GROUP_ATTRS;
private static LdapProvisioning SINGLETON = null;
private static synchronized void ensureSingleton(LdapProvisioning prov) {
if (SINGLETON != null) {
// pass an exception to have the stack logged
Zimbra.halt("Only one instance of LdapProvisioning can be created",
ServiceException.FAILURE("failed to instantiate LdapProvisioning", null));
}
SINGLETON = prov;
}
public LdapProvisioning() {
this(CacheMode.DEFAULT);
}
public LdapProvisioning(CacheMode cacheMode) {
ensureSingleton(this);
useCache = true;
if (cacheMode == CacheMode.OFF) {
useCache = false;
}
if (this.useCache) {
cache = new LdapCache.LRUMapCache();
} else {
cache = new LdapCache.NoopCache();
}
accountCache = cache.accountCache();
cosCache = cache.cosCache();
domainCache = cache.domainCache();
groupCache = cache.groupCache();
mimeTypeCache = cache.mimeTypeCache();
serverCache = cache.serverCache();
ucServiceCache = cache.ucServiceCache();
shareLocatorCache = cache.shareLocatorCache();
xmppComponentCache = cache.xmppComponentCache();
zimletCache = cache.zimletCache();
setDIT();
setHelper(new ZLdapHelper(this));
allDLs = new Groups(this);
filterFactory = ZLdapFilterFactory.getInstance();
try {
BASIC_DL_ATTRS = getBasicDLAttrs();
BASIC_DYNAMIC_GROUP_ATTRS = getBasicDynamicGroupAttrs();
BASIC_GROUP_ATTRS = getBasicGroupAttrs();
} catch (ServiceException e) {
Zimbra.halt("failed to initialize LdapProvisioning", e);
}
register(new Validators.DomainAccountValidator());
register(new Validators.DomainMaxAccountsValidator());
}
@Override
public int getAccountCacheSize() { return accountCache.getSize(); }
@Override
public double getAccountCacheHitRate() { return accountCache.getHitRate(); }
@Override
public int getCosCacheSize() { return cosCache.getSize(); }
@Override
public double getCosCacheHitRate() { return cosCache.getHitRate(); }
@Override
public int getDomainCacheSize() { return domainCache.getSize(); }
@Override
public double getDomainCacheHitRate() { return domainCache.getHitRate(); }
@Override
public int getServerCacheSize() { return serverCache.getSize(); }
@Override
public double getServerCacheHitRate() { return serverCache.getHitRate(); }
@Override
public int getUCServiceCacheSize() { return ucServiceCache.getSize(); }
@Override
public double getUCServiceCacheHitRate() { return ucServiceCache.getHitRate(); }
@Override
public int getZimletCacheSize() { return zimletCache.getSize(); }
@Override
public double getZimletCacheHitRate() { return zimletCache.getHitRate(); }
@Override
public int getGroupCacheSize() { return groupCache.getSize(); }
@Override
public double getGroupCacheHitRate() { return groupCache.getHitRate(); }
@Override
public int getXMPPCacheSize() { return xmppComponentCache.getSize(); }
@Override
public double getXMPPCacheHitRate() { return xmppComponentCache.getHitRate(); }
private String[] getBasicDLAttrs() throws ServiceException {
AttributeManager attrMgr = AttributeManager.getInstance();
Set<String> dlAttrs = attrMgr.getAllAttrsInClass(AttributeClass.distributionList);
Set<String> attrs = Sets.newHashSet(dlAttrs);
attrs.add(Provisioning.A_objectClass);
attrs.remove(Provisioning.A_zimbraMailForwardingAddress); // the member attr
attrs.remove(Provisioning.A_zimbraMailTransport); // does not apply to DL
// remove deprecated attrs
for (Iterator<String> iter = attrs.iterator(); iter.hasNext();) {
String attr = iter.next();
AttributeInfo ai = attrMgr.getAttributeInfo(attr);
if (ai != null && ai.isDeprecated()) {
iter.remove();
}
}
return Lists.newArrayList(attrs).toArray(new String[attrs.size()]);
}
private String[] getBasicDynamicGroupAttrs() throws ServiceException {
AttributeManager attrMgr = AttributeManager.getInstance();
Set<String> dynGroupAttrs = attrMgr.getAllAttrsInClass(AttributeClass.group);
Set<String> attrs = Sets.newHashSet(dynGroupAttrs);
attrs.add(Provisioning.A_objectClass);
// remove deprecated attrs
for (Iterator<String> iter = attrs.iterator(); iter.hasNext();) {
String attr = iter.next();
AttributeInfo ai = attrMgr.getAttributeInfo(attr);
if (ai != null && ai.isDeprecated()) {
iter.remove();
}
}
return Lists.newArrayList(attrs).toArray(new String[attrs.size()]);
}
private String[] getBasicGroupAttrs() throws ServiceException {
Set<String> attrs = Sets.newHashSet();
Set<String> dlAttrs = Sets.newHashSet(getBasicDLAttrs());
Set<String> dynGroupAttrs = Sets.newHashSet(getBasicDynamicGroupAttrs());
SetUtil.union(attrs, dlAttrs, dynGroupAttrs);
return Lists.newArrayList(attrs).toArray(new String[attrs.size()]);
}
/*
* Contains parallel arrays of old addrs and new addrs as a result of domain change
*/
protected static class ReplaceAddressResult {
ReplaceAddressResult(String oldAddrs[], String newAddrs[]) {
mOldAddrs = oldAddrs;
mNewAddrs = newAddrs;
}
private String mOldAddrs[];
private String mNewAddrs[];
public String[] oldAddrs() { return mOldAddrs; }
public String[] newAddrs() { return mNewAddrs; }
}
@Override
public void modifyAttrs(Entry e, Map<String, ? extends Object> attrs, boolean checkImmutable)
throws ServiceException {
modifyAttrs(e, attrs, checkImmutable, true);
}
/**
* Modifies this entry. <code>attrs</code> is a <code>Map</code> consisting of
* keys that are <code>String</code>s, and values that are either
* <ul>
* <li><code>null</code>, in which case the attr is removed</li>
* <li>a single <code>Object</code>, in which case the attr is modified
* based on the object's <code>toString()</code> value</li>
* <li>an <code>Object</code> array or <code>Collection</code>,
* in which case a multi-valued attr is updated</li>
* </ul>
*/
@Override
public void modifyAttrs(Entry e, Map<String, ? extends Object> attrs,
boolean checkImmutable, boolean allowCallback)
throws ServiceException {
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.MODIFY);
AttributeManager.getInstance().preModify(attrs, e, callbackContext, checkImmutable, allowCallback);
modifyAttrsInternal(e, null, attrs);
AttributeManager.getInstance().postModify(attrs, e, callbackContext, allowCallback);
}
@Override
public void restoreAccountAttrs(Account acct, Map<String, ? extends Object> backupAttrs)
throws ServiceException {
Map<String, Object> attrs = Maps.newHashMap(backupAttrs);
Object ocsInBackupObj = backupAttrs.get(A_objectClass);
String[] ocsInBackup = StringUtil.toStringArray(ocsInBackupObj);
String[] ocsOnAcct = acct.getMultiAttr(A_objectClass);
// replace A_objectClass in backupAttrs with only OCs that is not a
// super OC of LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC, then merge them with
// OCs added during restoreAccount.
List<String> needOCs = Lists.newArrayList(ocsOnAcct);
for (String oc : ocsInBackup) {
if (!LdapObjectClassHierarchy.isSuperiorOC(this, LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC, oc)) {
if (!needOCs.contains(oc)) {
needOCs.add(oc);
}
}
}
attrs.put(A_objectClass, needOCs.toArray(new String[needOCs.size()]));
modifyAttrs(acct, attrs, false, false);
}
/**
* should only be called internally.
*
* @param initCtxt
* @param attrs
* @throws ServiceException
*/
protected void modifyAttrsInternal(Entry entry, ZLdapContext initZlc,
Map<String, ? extends Object> attrs)
throws ServiceException {
if (entry instanceof Account && !(entry instanceof CalendarResource)) {
Account acct = (Account) entry;
validate(ProvisioningValidator.MODIFY_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE,
acct.getAttr(A_zimbraMailDeliveryAddress), attrs, acct);
}
modifyLdapAttrs(entry, initZlc, attrs);
}
private void modifyLdapAttrs(Entry entry, ZLdapContext initZlc,
Map<String, ? extends Object> attrs)
throws ServiceException {
ZLdapContext zlc = initZlc;
try {
if (zlc == null) {
zlc = LdapClient.getContext(LdapServerType.MASTER,
LdapUsage.modifyEntryfromEntryType(entry.getEntryType()));
}
helper.modifyAttrs(zlc, ((LdapEntry)entry).getDN(), attrs, entry);
} catch (LdapInvalidAttrNameException e) {
throw AccountServiceException.INVALID_ATTR_NAME(
"invalid attr name: " + e.getMessage(), e);
} catch (LdapInvalidAttrValueException e) {
throw AccountServiceException.INVALID_ATTR_VALUE(
"invalid attr value: " + e.getMessage(), e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to modify attrs: "
+ e.getMessage(), e);
} finally {
refreshEntry(entry, zlc);
if (initZlc == null) {
LdapClient.closeContext(zlc);
}
}
}
/**
* reload/refresh the entry from the ***master***.
*/
@Override
public void reload(Entry e) throws ServiceException {
reload(e, true);
}
@Override
public void reload(Entry e, boolean master) throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.get(master), LdapUsage.GET_ENTRY);
refreshEntry(e, zlc);
} finally {
LdapClient.closeContext(zlc);
}
}
void refreshEntry(Entry entry, ZLdapContext initZlc) throws ServiceException {
try {
String dn = ((LdapEntry)entry).getDN();
ZAttributes attributes = helper.getAttributes(initZlc, dn);
Map<String, Object> attrs = attributes.getAttrs();
Map<String,Object> defaults = null;
Map<String,Object> secondaryDefaults = null;
if (entry instanceof Account) {
//
// We can get here from either modifyAttrsInternal or reload path.
//
// If we got here from modifyAttrsInternal, zimbraCOSId on account
// might have been changed, added, removed, but entry now still contains
// the old attrs. Create a temp Account object from the new attrs, and then
// use the same cos of the temp Account object for our entry object.
//
// If we got here from reload, attrs are likely not changed, the callsites
// just want a refreshed object. For this case it's best if we still
// always resolve the COS correctly. makeAccount is a cheap call and won't
// add any overhead like loading cos/domain from LDAP: even if cos/domain
// has to be loaded (because not in cache) in the getCOS(temp) call, it's
// just the same as calling (buggy) getCOS(entry) before.
//
// We only need the temp object for the getCOS call, don't need to setup
// primary/secondary defaults on the temp object because:
// zimbraCOSId is only on account(of course), and that's all needed
// for determining the COS for the account in the getCOS call: if
// zimbraCOSId is not set on account, it will fallback to the domain
// default COS, then fallback to the system default COS.
//
Account temp = makeAccountNoDefaults(dn, attributes);
Cos cos = getCOS(temp);
if (cos != null)
defaults = cos.getAccountDefaults();
Domain domain = getDomain((Account)entry);
if (domain != null)
secondaryDefaults = domain.getAccountDefaults();
} else if (entry instanceof Domain) {
defaults = getConfig().getDomainDefaults();
} else if (entry instanceof Server) {
defaults = getConfig().getServerDefaults();
}
if (defaults == null && secondaryDefaults == null)
entry.setAttrs(attrs);
else
entry.setAttrs(attrs, defaults, secondaryDefaults);
extendLifeInCacheOrFlush(entry);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to refresh entry", e);
}
}
public void extendLifeInCacheOrFlush(Entry entry) {
if (entry instanceof Account) {
accountCache.replace((Account)entry);
} else if (entry instanceof LdapCos) {
cosCache.replace((LdapCos)entry);
} else if (entry instanceof Domain) {
domainCache.replace((Domain)entry);
} else if (entry instanceof Server) {
serverCache.replace((Server)entry);
} else if (entry instanceof UCService) {
ucServiceCache.replace((UCService)entry);
} else if (entry instanceof XMPPComponent) {
xmppComponentCache.replace((XMPPComponent)entry);
} else if (entry instanceof LdapZimlet) {
zimletCache.replace((LdapZimlet)entry);
} else if (entry instanceof Group) {
/*
* DLs returned by Provisioning.get(DistributionListBy) and
* DLs/dynamic groups returned by Provisioning.getGroup(DistributionListBy)
* are "not" cached.
*
* DLs returned by Provisioning.getDLBasic(DistributionListBy) and
* DLs/dynamic groups returned by Provisioning.getGroupBasic(DistributionListBy)
* "are" cached.
*
* Need to flush out the cached entries if the instance being modified is not
* in cache. (i.e. the instance being modified was obtained by get/getGroup)
*/
Group modifiedInstance = (Group) entry;
Group cachedInstance = getGroupFromCache(DistributionListBy.id, modifiedInstance.getId());
if (cachedInstance != null && modifiedInstance != cachedInstance) {
groupCache.remove(cachedInstance);
}
}
}
/**
* Status check on LDAP connection. Search for global config entry.
*/
@Override
public boolean healthCheck() throws ServiceException {
boolean result = false;
try {
ZAttributes attrs = helper.getAttributes(LdapUsage.HEALTH_CHECK, mDIT.configDN());
result = attrs != null; // not really needed, getAttributes should never return null
} catch (ServiceException e) {
mLog.warn("LDAP health check error", e);
}
return result;
}
@Override
public synchronized Config getConfig() throws ServiceException
{
if (cachedGlobalConfig == null) {
String configDn = mDIT.configDN();
try {
ZAttributes attrs = helper.getAttributes(LdapUsage.GET_GLOBALCONFIG, configDn);
LdapConfig config = new LdapConfig(configDn, attrs, this);
if (useCache) {
cachedGlobalConfig = config;
} else {
return config;
}
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to get config", e);
}
}
return cachedGlobalConfig;
}
@Override
public synchronized GlobalGrant getGlobalGrant() throws ServiceException
{
if (cachedGlobalGrant == null) {
String globalGrantDn = mDIT.globalGrantDN();
try {
ZAttributes attrs = helper.getAttributes(LdapUsage.GET_GLOBALGRANT, globalGrantDn);
LdapGlobalGrant globalGrant = new LdapGlobalGrant(globalGrantDn, attrs, this);
if (useCache) {
cachedGlobalGrant = globalGrant;
} else {
return globalGrant;
}
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to get globalgrant", e);
}
}
return cachedGlobalGrant;
}
@Override
public List<MimeTypeInfo> getMimeTypes(String mimeType) throws ServiceException {
return mimeTypeCache.getMimeTypes(this, mimeType);
}
@Override
public List<MimeTypeInfo> getMimeTypesByQuery(String mimeType) throws ServiceException {
List<MimeTypeInfo> mimeTypes = new ArrayList<MimeTypeInfo>();
try {
ZSearchResultEnumeration ne = helper.searchDir(mDIT.mimeBaseDN(),
filterFactory.mimeEntryByMimeType(mimeType), ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
mimeTypes.add(new LdapMimeType(sr, this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to get mime types for " + mimeType, e);
}
return mimeTypes;
}
@Override
public List<MimeTypeInfo> getAllMimeTypes() throws ServiceException {
return mimeTypeCache.getAllMimeTypes(this);
}
@Override
public List<MimeTypeInfo> getAllMimeTypesByQuery() throws ServiceException {
List<MimeTypeInfo> mimeTypes = new ArrayList<MimeTypeInfo>();
try {
ZSearchResultEnumeration ne = helper.searchDir(
mDIT.mimeBaseDN(), filterFactory.allMimeEntries(),
ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
mimeTypes.add(new LdapMimeType(sr, this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to get mime types", e);
}
return mimeTypes;
}
private Account getAccountByQuery(String base, ZLdapFilter filter, ZLdapContext initZlc,
boolean loadFromMaster)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(base, filter, initZlc, loadFromMaster);
if (sr != null) {
return makeAccount(sr.getDN(), sr.getAttributes());
}
} catch (LdapMultipleEntriesMatchedException e) {
// duped entries are not in the exception, log it
ZimbraLog.account.debug(e.getMessage());
throw AccountServiceException.MULTIPLE_ACCOUNTS_MATCHED(
String.format("multiple entries are returned by query: base=%s, query=%s",
e.getQueryBase(), e.getQuery()));
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup account via query: " +
filter.toFilterString() + " message: "+e.getMessage(), e);
}
return null;
}
private Account getAccountById(String zimbraId, ZLdapContext zlc, boolean loadFromMaster)
throws ServiceException {
if (zimbraId == null)
return null;
Account a = accountCache.getById(zimbraId);
if (a == null) {
ZLdapFilter filter = filterFactory.accountById(zimbraId);
a = getAccountByQuery(mDIT.mailBranchBaseDN(), filter, zlc, loadFromMaster);
// search again under the admin base if not found and admin base is not under mail base
if (a == null && !mDIT.isUnder(mDIT.mailBranchBaseDN(), mDIT.adminBaseDN()))
a = getAccountByQuery(mDIT.adminBaseDN(), filter, zlc, loadFromMaster);
accountCache.put(a);
}
return a;
}
@Override
public Account get(AccountBy keyType, String key) throws ServiceException {
return get(keyType, key, false);
}
@Override
public Account get(AccountBy keyType, String key, boolean loadFromMaster)
throws ServiceException {
switch(keyType) {
case adminName:
return getAdminAccountByName(key, loadFromMaster);
case appAdminName:
return getAppAdminAccountByName(key, loadFromMaster);
case id:
return getAccountById(key, null, loadFromMaster);
case foreignPrincipal:
return getAccountByForeignPrincipal(key, loadFromMaster);
case name:
return getAccountByName(key, loadFromMaster);
case krb5Principal:
return Krb5Principal.getAccountFromKrb5Principal(key, loadFromMaster);
default:
return null;
}
}
public Account getFromCache(AccountBy keyType, String key) throws ServiceException {
switch(keyType) {
case adminName:
return accountCache.getByName(key);
case id:
return accountCache.getById(key);
case foreignPrincipal:
return accountCache.getByForeignPrincipal(key);
case name:
return accountCache.getByName(key);
case krb5Principal:
throw ServiceException.FAILURE("key type krb5Principal is not supported by getFromCache", null);
default:
return null;
}
}
private Account getAccountByForeignPrincipal(String foreignPrincipal, boolean loadFromMaster)
throws ServiceException {
Account a = accountCache.getByForeignPrincipal(foreignPrincipal);
// bug 27966, always do a search so dup entries can be thrown
Account acct = getAccountByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.accountByForeignPrincipal(foreignPrincipal),
null, loadFromMaster);
// all is well, put the account in cache if it was not in cache
// this is so we don't change our caching behavior - the above search was just to check for dup - we did that anyway
// before bug 23372 was fixed.
if (a == null) {
a = acct;
accountCache.put(a);
}
return a;
}
private Account getAdminAccountByName(String name, boolean loadFromMaster)
throws ServiceException {
Account a = accountCache.getByName(name);
if (a == null) {
a = getAccountByQuery(
mDIT.adminBaseDN(),
filterFactory.adminAccountByRDN(mDIT.accountNamingRdnAttr(), name),
null, loadFromMaster);
accountCache.put(a);
}
return a;
}
private Account getAppAdminAccountByName(String name, boolean loadFromMaster)
throws ServiceException {
Account a = accountCache.getByName(name);
if (a == null) {
a = getAccountByQuery(
mDIT.appAdminBaseDN(),
filterFactory.adminAccountByRDN(mDIT.accountNamingRdnAttr(), name),
null, loadFromMaster);
accountCache.put(a);
}
return a;
}
private String fixupAccountName(String emailAddress) throws ServiceException {
int index = emailAddress.indexOf('@');
String domain = null;
if (index == -1) {
// domain is already in ASCII name
domain = getConfig().getAttr(Provisioning.A_zimbraDefaultDomainName, null);
if (domain == null)
throw ServiceException.INVALID_REQUEST("must be valid email address: "+emailAddress, null);
else
emailAddress = emailAddress + "@" + domain;
} else
emailAddress = IDNUtil.toAsciiEmail(emailAddress);
return emailAddress;
}
Account getAccountByName(String emailAddress, boolean loadFromMaster)
throws ServiceException {
return getAccountByName(emailAddress, loadFromMaster, true);
}
Account getAccountByName(String emailAddress, boolean loadFromMaster, boolean checkAliasDomain)
throws ServiceException {
Account account = getAccountByNameInternal(emailAddress, loadFromMaster);
// if not found, see if the domain is an alias domain and if so try to
// get account by the alias domain target
if (account == null) {
if (checkAliasDomain) {
String addrByDomainAlias = getEmailAddrByDomainAlias(emailAddress);
if (addrByDomainAlias != null) {
account = getAccountByNameInternal(addrByDomainAlias, loadFromMaster);
}
}
}
return account;
}
private Account getAccountByNameInternal(String emailAddress, boolean loadFromMaster)
throws ServiceException {
emailAddress = fixupAccountName(emailAddress);
Account account = accountCache.getByName(emailAddress);
if (account == null) {
account = getAccountByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.accountByName(emailAddress),
null, loadFromMaster);
accountCache.put(account);
}
return account;
}
@Override
public Account getAccountByForeignName(String foreignName, String application, Domain domain)
throws ServiceException {
// first try direct match
Account acct = getAccountByForeignPrincipal(application + ":" + foreignName);
if (acct != null)
return acct;
if (domain == null) {
String parts[] = foreignName.split("@");
if (parts.length != 2)
return null;
String domainName = parts[1];
domain = getDomain(Key.DomainBy.foreignName, application + ":" + domainName, true);
}
if (domain == null)
return null;
// see if there is a custom hander on the domain
DomainNameMappingHandler.HandlerConfig handlerConfig =
DomainNameMappingHandler.getHandlerConfig(domain, application);
String acctName;
if (handlerConfig != null) {
// invoke the custom handler
acctName = DomainNameMappingHandler.mapName(handlerConfig, foreignName, domain.getName());
} else {
// do our builtin mapping of {localpart}@{zimbra domain name}
acctName = foreignName.split("@")[0] + "@" + domain.getName();
}
return get(AccountBy.name, acctName);
}
private Cos lookupCos(String key, ZLdapContext zlc) throws ServiceException {
Cos c = null;
c = getCosById(key, zlc);
if (c == null)
c = getCosByName(key, zlc);
if (c == null)
throw AccountServiceException.NO_SUCH_COS(key);
else
return c;
}
@Override
public void autoProvAccountEager(EagerAutoProvisionScheduler scheduler)
throws ServiceException {
AutoProvisionEager.handleScheduledDomains(this, scheduler);
}
@Override
public Account autoProvAccountLazy(Domain domain, String loginName,
String loginPassword, AutoProvAuthMech authMech)
throws ServiceException {
AutoProvisionLazy autoPorv =
new AutoProvisionLazy(this, domain, loginName, loginPassword, authMech);
return autoPorv.handle();
}
@Override
public Account autoProvAccountManual(Domain domain, AutoProvPrincipalBy by,
String principal, String password)
throws ServiceException {
AutoProvisionManual autoProv =
new AutoProvisionManual(this, domain, by, principal, password);
return autoProv.handle();
}
@Override
public void searchAutoProvDirectory(Domain domain, String filter, String name,
String[] returnAttrs, int maxResults, DirectoryEntryVisitor visitor)
throws ServiceException {
AutoProvision.searchAutoProvDirectory(this, domain, filter, name, null,
returnAttrs, maxResults, visitor);
}
@Override
public Account createAccount(String emailAddress, String password, Map<String, Object> attrs)
throws ServiceException {
return createAccount(emailAddress, password, attrs,
mDIT.handleSpecialAttrs(attrs), null, false, null);
}
@Override
public Account restoreAccount(String emailAddress, String password,
Map<String, Object> attrs, Map<String, Object> origAttrs)
throws ServiceException {
return createAccount(emailAddress, password, attrs,
mDIT.handleSpecialAttrs(attrs), null, true, origAttrs);
}
private Account createAccount(String emailAddress, String password,
Map<String, Object> acctAttrs, SpecialAttrs specialAttrs,
String[] additionalObjectClasses,
boolean restoring, Map<String, Object> origAttrs)
throws ServiceException {
String uuid = specialAttrs.getZimbraId();
String baseDn = specialAttrs.getLdapBaseDn();
emailAddress = emailAddress.toLowerCase().trim();
String parts[] = emailAddress.split("@");
if (parts.length != 2) {
throw ServiceException.INVALID_REQUEST("must be valid email address: " +
emailAddress, null);
}
String localPart = parts[0];
String domain = parts[1];
domain = IDNUtil.toAsciiDomainName(domain);
emailAddress = localPart + "@" + domain;
validEmailAddress(emailAddress);
if (restoring) {
validate(ProvisioningValidator.CREATE_ACCOUNT,
emailAddress, additionalObjectClasses, origAttrs);
validate(ProvisioningValidator.CREATE_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE,
emailAddress, origAttrs);
} else {
validate(ProvisioningValidator.CREATE_ACCOUNT,
emailAddress, additionalObjectClasses, acctAttrs);
validate(ProvisioningValidator.CREATE_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE,
emailAddress, acctAttrs);
}
if (acctAttrs == null) {
acctAttrs = new HashMap<String, Object>();
}
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
callbackContext.setCreatingEntryName(emailAddress);
AttributeManager.getInstance().preModify(acctAttrs, null, callbackContext, true);
Account acct = null;
String dn = null;
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_ACCOUNT);
Domain d = getDomainByAsciiName(domain, zlc);
if (d == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(domain);
}
if (!d.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(acctAttrs);
for (int i=0; i < sInvalidAccountCreateModifyAttrs.length; i++) {
String a = sInvalidAccountCreateModifyAttrs[i];
if (entry.hasAttribute(a))
throw ServiceException.INVALID_REQUEST("invalid attribute for CreateAccount: "+a, null);
}
Set<String> ocs;
if (additionalObjectClasses == null) {
// We are creating a pure account object, get all object classes for account.
//
// If restoring, only add zimbra default object classes, do not add extra
// ones configured. After createAccount, the restore code will issue a
// modifyAttrs call and all object classes in the backed up account will be
// in the attr map passed to modifyAttrs.
//
ocs = LdapObjectClass.getAccountObjectClasses(this, restoring);
} else {
// We are creating a "subclass" of account (e.g. calendar resource), get just the
// zimbra default object classes for account, then add extra object classes needed
// by the subclass. All object classes needed by the subclass (calendar resource)
// were figured out in the createCalendarResource method: including the zimbra
// default (zimbracalendarResource) and any extra ones configured via
// globalconfig.zimbraCalendarResourceExtraObjectClass.
//
// It doesn't matter if the additionalObjectClasses already contains object classes
// added by the getAccountObjectClasses(this, true). When additional object classes
// are added to the set, duplicated once will only appear once.
//
//
// The "restoring" flag is ignored in this path.
// When restoring a calendar a resource, the restoring code:
// - always calls createAccount, not createCalendarResource
// - always pass null for additionalObjectClasses
// - like restoring an account, it will call modifyAttrs after the
// entry is created, any object classes in the backed up data
// will be in the attr map passed to modifyAttrs.
ocs = LdapObjectClass.getAccountObjectClasses(this, true);
for (int i = 0; i < additionalObjectClasses.length; i++)
ocs.add(additionalObjectClasses[i]);
}
/* bug 48226
*
* Check if any of the OCs in the backup is a structural OC that subclasses
* our default OC (defined in ZIMBRA_DEFAULT_PERSON_OC).
* If so, add that OC now while creating the account, because it cannot be modified later.
*/
if (restoring && origAttrs != null) {
Object ocsInBackupObj = origAttrs.get(A_objectClass);
String[] ocsInBackup = StringUtil.toStringArray(ocsInBackupObj);
String mostSpecificOC = LdapObjectClassHierarchy.getMostSpecificOC(
this, ocsInBackup, LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC);
if (!LdapObjectClass.ZIMBRA_DEFAULT_PERSON_OC.equalsIgnoreCase(mostSpecificOC)) {
ocs.add(mostSpecificOC);
}
}
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr;
if (uuid == null) {
zimbraIdStr = LdapUtil.generateUUID();
} else {
zimbraIdStr = uuid;
}
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
// default account status is active
if (!entry.hasAttribute(Provisioning.A_zimbraAccountStatus)) {
entry.setAttr(A_zimbraAccountStatus, Provisioning.ACCOUNT_STATUS_ACTIVE);
}
Cos cos = null;
String cosId = entry.getAttrString(Provisioning.A_zimbraCOSId);
if (cosId != null) {
cos = lookupCos(cosId, zlc);
if (!cos.getId().equals(cosId)) {
cosId = cos.getId();
}
entry.setAttr(Provisioning.A_zimbraCOSId, cosId);
} else {
String domainCosId =
domain != null ?
isExternalVirtualAccount(entry) ?
d.getDomainDefaultExternalUserCOSId() :
d.getDomainDefaultCOSId() :
null;
if (domainCosId != null) {
cos = get(Key.CosBy.id, domainCosId);
}
if (cos == null) {
cos = getCosByName(isExternalVirtualAccount(entry) ?
Provisioning.DEFAULT_EXTERNAL_COS_NAME : Provisioning.DEFAULT_COS_NAME,
zlc);
}
}
boolean hasMailTransport = entry.hasAttribute(Provisioning.A_zimbraMailTransport);
// if zimbraMailTransport is NOT provided, pick a server and add
// zimbraMailHost(and zimbraMailTransport) if it is not specified
if (!hasMailTransport) {
addMailHost(entry, cos, true);
}
// set all the mail-related attrs if zimbraMailHost or zimbraMailTransport was specified
if (entry.hasAttribute(Provisioning.A_zimbraMailHost) ||
entry.hasAttribute(Provisioning.A_zimbraMailTransport)) {
// default mail status is enabled
if (!entry.hasAttribute(Provisioning.A_zimbraMailStatus)) {
entry.setAttr(A_zimbraMailStatus, MAIL_STATUS_ENABLED);
}
// default account mail delivery address is email address
if (!entry.hasAttribute(Provisioning.A_zimbraMailDeliveryAddress)) {
entry.setAttr(A_zimbraMailDeliveryAddress, emailAddress);
}
} else {
throw ServiceException.INVALID_REQUEST("missing " +
Provisioning.A_zimbraMailHost + " or " + Provisioning.A_zimbraMailTransport +
" for CreateAccount: " + emailAddress, null);
}
// amivisAccount requires the mail attr, so we always add it
entry.setAttr(A_mail, emailAddress);
// required for ZIMBRA_DEFAULT_PERSON_OC class
if (!entry.hasAttribute(Provisioning.A_cn)) {
String displayName = entry.getAttrString(Provisioning.A_displayName);
if (displayName != null) {
entry.setAttr(A_cn, displayName);
} else {
entry.setAttr(A_cn, localPart);
}
}
// required for ZIMBRA_DEFAULT_PERSON_OC class
if (!entry.hasAttribute(Provisioning.A_sn)) {
entry.setAttr(A_sn, localPart);
}
entry.setAttr(A_uid, localPart);
setInitialPassword(cos, entry, password);
String ucPassword = entry.getAttrString(Provisioning.A_zimbraUCPassword);
if (ucPassword != null) {
String encryptedPassword = Account.encrypytUCPassword(
entry.getAttrString(Provisioning.A_zimbraId), ucPassword);
entry.setAttr(Provisioning.A_zimbraUCPassword, encryptedPassword);
}
dn = mDIT.accountDNCreate(baseDn, entry.getAttributes(), localPart, domain);
entry.setDN(dn);
zlc.createEntry(entry);
acct = getAccountById(zimbraIdStr, zlc, true);
if (acct == null) {
throw ServiceException.FAILURE(
"unable to get account after creating LDAP account entry: " +
emailAddress + ", check ldap log for possible BDB deadlock", null);
}
AttributeManager.getInstance().postModify(acctAttrs, acct, callbackContext);
removeExternalAddrsFromAllDynamicGroups(acct.getAllAddrsSet(), zlc);
validate(ProvisioningValidator.CREATE_ACCOUNT_SUCCEEDED,
emailAddress, acct);
return acct;
} catch (LdapEntryAlreadyExistException e) {
throw AccountServiceException.ACCOUNT_EXISTS(emailAddress, dn, e);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create account: "+emailAddress, e);
} finally {
LdapClient.closeContext(zlc);
if (!restoring && acct != null) {
for (PostCreateAccountListener listener : ProvisioningExt.getPostCreateAccountListeners()) {
if (listener.enabled()) {
listener.handle(acct);
}
}
}
}
}
private boolean isExternalVirtualAccount(ZMutableEntry entry) throws LdapException {
return entry.hasAttribute(Provisioning.A_zimbraIsExternalVirtualAccount) &&
ProvisioningConstants.TRUE.equals(entry.getAttrString(Provisioning.A_zimbraIsExternalVirtualAccount));
}
@Override
public void searchOCsForSuperClasses(Map<String, Set<String>> ocs) {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.GET_SCHEMA);
ZLdapSchema schema = zlc.getSchema();
for (Map.Entry<String, Set<String>> entry : ocs.entrySet()) {
String oc = entry.getKey();
Set<String> superOCs = entry.getValue();
try {
ZimbraLog.account.debug("Looking up OC: " + oc);
ZLdapSchema.ZObjectClassDefinition ocSchema = schema.getObjectClass(oc);
if (ocSchema != null) {
List<String> superClasses = ocSchema.getSuperiorClasses();
for (String superOC : superClasses) {
superOCs.add(superOC.toLowerCase());
}
}
} catch (ServiceException e) {
ZimbraLog.account.debug("unable to load LDAP schema extension for objectclass: " + oc, e);
}
}
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get LDAP schema", e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void getAttrsInOCs(String[] ocs, Set<String> attrsInOCs)
throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.GET_SCHEMA);
ZLdapSchema schema = zlc.getSchema();
for (String oc : ocs) {
try {
ZLdapSchema.ZObjectClassDefinition ocSchema = schema.getObjectClass(oc);
if (ocSchema != null) {
List<String> optAttrs = ocSchema.getOptionalAttributes();
for (String attr : optAttrs) {
attrsInOCs.add(attr);
}
List<String> reqAttrs = ocSchema.getRequiredAttributes();
for (String attr : reqAttrs) {
attrsInOCs.add(attr);
}
}
} catch (ServiceException e) {
ZimbraLog.account.debug("unable to lookup attributes for objectclass: " + oc, e);
}
}
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get LDAP schema", e);
} finally {
LdapClient.closeContext(zlc);
}
}
private void setMailHost(ZMutableEntry entry, Server server, boolean setMailTransport) {
String serviceHostname = server.getAttr(Provisioning.A_zimbraServiceHostname);
entry.setAttr(Provisioning.A_zimbraMailHost, serviceHostname);
if (setMailTransport) {
int lmtpPort = server.getIntAttr(Provisioning.A_zimbraLmtpBindPort,
com.zimbra.cs.util.Config.D_LMTP_BIND_PORT);
String transport = "lmtp:" + serviceHostname + ":" + lmtpPort;
entry.setAttr(Provisioning.A_zimbraMailTransport, transport);
}
}
private boolean addDefaultMailHost(ZMutableEntry entry, Server server, boolean setMailTransport)
throws ServiceException {
String serviceHostname = server.getAttr(Provisioning.A_zimbraServiceHostname);
if (server.hasMailboxService() && serviceHostname != null) {
setMailHost(entry, server, setMailTransport);
return true;
}
return false;
}
private void addDefaultMailHost(ZMutableEntry entry, boolean setMailTransport)
throws ServiceException {
if (!addDefaultMailHost(entry, getLocalServer(), setMailTransport)) {
for (Server server: getAllServers()) {
if (addDefaultMailHost(entry, server, setMailTransport)) {
return;
}
}
}
}
private void addMailHost(ZMutableEntry entry, Cos cos, boolean setMailTransport)
throws ServiceException {
// if zimbraMailHost is not specified, and we have a COS, see if there is
// a pool to pick from.
if (cos != null && !entry.hasAttribute(Provisioning.A_zimbraMailHost)) {
String mailHostPool[] = cos.getMultiAttr(Provisioning.A_zimbraMailHostPool);
addMailHost(entry, mailHostPool, cos.getName(), setMailTransport);
}
// if zimbraMailHost still not specified, default to local server's
// zimbraServiceHostname if it has the mailbox service enabled, otherwise
// look through all servers and pick first with the service enabled.
// this means every account will always have a mailbox
if (!entry.hasAttribute(Provisioning.A_zimbraMailHost)) {
addDefaultMailHost(entry, setMailTransport);
}
}
private String addMailHost(ZMutableEntry entry, String[] mailHostPool, String cosName,
boolean setMailTransport)
throws ServiceException {
if (mailHostPool.length == 0) {
return null;
} else if (mailHostPool.length > 1) {
// copy it, since we are dealing with a cached String[]
String pool[] = new String[mailHostPool.length];
System.arraycopy(mailHostPool, 0, pool, 0, mailHostPool.length);
mailHostPool = pool;
}
// Shuffle up and deal
int max = mailHostPool.length;
while (max > 0) {
int i = sPoolRandom.nextInt(max);
String mailHostId = mailHostPool[i];
Server s = (mailHostId == null) ? null : getServerByIdInternal(mailHostId);
if (s != null) {
String mailHost = s.getAttr(Provisioning.A_zimbraServiceHostname);
if (mailHost != null) {
if (s.hasMailboxService()) {
setMailHost(entry, s, setMailTransport);
return mailHost;
} else {
ZimbraLog.account.warn("cos("+cosName+") mailHostPool server(" +
s.getName()+") is not enabled for mailbox service");
}
} else {
ZimbraLog.account.warn("cos("+cosName+") mailHostPool server(" +
s.getName()+") has no service hostname");
}
} else {
ZimbraLog.account.warn("cos("+cosName+") has invalid server in pool: "+mailHostId);
}
if (i != max-1) {
mailHostPool[i] = mailHostPool[max-1];
}
max--;
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public List<Account> getAllAdminAccounts() throws ServiceException {
SearchAccountsOptions opts = new SearchAccountsOptions();
opts.setFilter(filterFactory.allAdminAccounts());
opts.setIncludeType(IncludeType.ACCOUNTS_ONLY);
opts.setSortOpt(SortOpt.SORT_ASCENDING);
return (List<Account>) searchDirectoryInternal(opts);
}
@Override
public void searchAccountsOnServer(Server server, SearchAccountsOptions opts,
NamedEntry.Visitor visitor)
throws ServiceException {
searchAccountsOnServerInternal(server, opts, visitor);
}
@Override
public List<NamedEntry> searchAccountsOnServer(Server server, SearchAccountsOptions opts)
throws ServiceException {
return searchAccountsOnServerInternal(server, opts, null);
}
private List<NamedEntry> searchAccountsOnServerInternal(Server server,
SearchAccountsOptions options, NamedEntry.Visitor visitor)
throws ServiceException {
// filter cannot be set
if (options.getFilter() != null || options.getFilterString() != null) {
throw ServiceException.INVALID_REQUEST(
"cannot set filter for searchAccountsOnServer", null);
}
if (server == null) {
throw ServiceException.INVALID_REQUEST(
"missing server", null);
}
IncludeType includeType = options.getIncludeType();
/*
* This is the ONLY place where search filter can be affected by domain, because
* we have to support custom DIT where account/cr entries are NOT populated under
* the domain tree. In our default LdapDIT implementation, domain is always
* ignored in the filterXXX(domain, server) calls.
*
* Would be great if we don't have to support custom DIT someday.
*/
Domain domain = options.getDomain();
ZLdapFilter filter;
if (includeType == IncludeType.ACCOUNTS_AND_CALENDAR_RESOURCES) {
filter = mDIT.filterAccountsByDomainAndServer(domain, server);
} else if (includeType == IncludeType.ACCOUNTS_ONLY) {
filter = mDIT.filterAccountsOnlyByDomainAndServer(domain, server);
} else {
filter = mDIT.filterCalendarResourceByDomainAndServer(domain, server);
}
options.setFilter(filter);
return searchDirectoryInternal(options, visitor);
}
@Override
public List<NamedEntry> searchDirectory(SearchDirectoryOptions options)
throws ServiceException {
return searchDirectoryInternal(options, null);
}
@Override
public void searchDirectory(SearchDirectoryOptions options, NamedEntry.Visitor visitor)
throws ServiceException {
searchDirectoryInternal(options, visitor);
}
private List<?> searchDirectoryInternal(SearchDirectoryOptions options)
throws ServiceException{
return searchDirectoryInternal(options, null);
}
private String[] getSearchBases(Domain domain, Set<ObjectType> types)
throws ServiceException {
String[] bases;
if (domain != null) {
String domainDN = ((LdapDomain) domain).getDN();
boolean domainsTree = false;
boolean groupsTree = false;
boolean peopleTree = false;
if (types.contains(ObjectType.dynamicgroups)) {
groupsTree = true;
}
if (types.contains(ObjectType.accounts) ||
types.contains(ObjectType.aliases) ||
types.contains(ObjectType.distributionlists) ||
types.contains(ObjectType.resources)) {
peopleTree = true;
}
if (types.contains(ObjectType.domains)) {
domainsTree = true;
}
/*
* error if a domain is specified but non of domain-ed object types is specified.
*/
if (!groupsTree && !peopleTree && !domainsTree) {
throw ServiceException.INVALID_REQUEST(
"domain is specified but non of domain-ed types is specified", null);
}
/*
* error if both domain type and one on account/resource/group types are also
* requested. Because, for domains, we *do* want to return sub-domains;
* but for accounts/resources/groups, we only want entries in the specified
* domain, not sub-domains.
*
* e.g. if domains and accounts are requested, the search base would be the
* domains DN, then all accounts in sub-domains will also be returned. This
* can be worked out by the DN Subtree Match Filter:
* (||(objectClass=zimbraDomain)(&(objectClass=zimbraAccount)(DN-Subtree-Match-Filter)))
* but it will need some work in the existing code. This use case is not needed
* for now - just throw.
*/
if (domainsTree && (groupsTree || peopleTree)) {
throw ServiceException.FAILURE("specifying domains type and one of " +
"accounts/resources/groups type is not supported by in-memory LDAP server", null);
}
/*
* InMemoryDirectoryServer does not support EXTENSIBLE-MATCH filter.
*/
if (InMemoryLdapServer.isOn()) {
/*
* unit test path: DN Subtree Match Filter is not supported by InMemoryLdapServer
*
* If search for domains, case is the domains DN.
*
* If search for accounts/resources/groups:
* Search twice: once under the people tree, once under the groups tree,
* so entries under sub-domains are not returned.
*
*/
if (domainsTree) {
bases = new String[]{domainDN};
} else {
List<String> baseList = Lists.newArrayList();
if (groupsTree) {
baseList.add(mDIT.domainDNToDynamicGroupsBaseDN(domainDN));
}
if (peopleTree) {
baseList.add(mDIT.domainDNToAccountSearchDN(domainDN));
}
bases = baseList.toArray(new String[baseList.size()]);
}
} else {
/*
* production path
*
* use DN Subtree Match Filter and domain DN or base if objects in both
* people tree and groups tree are needed
*/
String searchBase;
if (domainsTree) {
searchBase = domainDN;
} else {
if ((groupsTree && peopleTree)) {
searchBase = domainDN;
} else if (groupsTree) {
searchBase = mDIT.domainDNToDynamicGroupsBaseDN(domainDN);
} else {
searchBase = mDIT.domainDNToAccountSearchDN(domainDN);
}
}
bases = new String[]{searchBase};
}
} else {
int flags = SearchDirectoryOptions.getTypesAsFlags(types);
bases = mDIT.getSearchBases(flags);
}
return bases;
}
private List<NamedEntry> searchDirectoryInternal(SearchDirectoryOptions options,
NamedEntry.Visitor visitor)
throws ServiceException {
Set<ObjectType> types = options.getTypes();
if (types == null) {
throw ServiceException.INVALID_REQUEST("missing types", null);
}
/*
* base
*/
Domain domain = options.getDomain();
String[] bases = getSearchBases(domain, types);
/*
* filter
*/
int flags = options.getTypesAsFlags();
ZLdapFilter filter = options.getFilter();
String filterStr = options.getFilterString();
// exact one of filter or filterString has to be set
if (filter != null && filterStr != null) {
throw ServiceException.INVALID_REQUEST("only one of filter or filterString can be set", null);
}
if (filter == null) {
if (options.getConvertIDNToAscii() && !Strings.isNullOrEmpty(filterStr)) {
filterStr = LdapEntrySearchFilter.toLdapIDNFilter(filterStr);
}
// prepend objectClass filters
String objectClass = getObjectClassQuery(flags);
if (filterStr == null || filterStr.equals("")) {
filterStr = objectClass;
} else {
if (filterStr.startsWith("(") && filterStr.endsWith(")")) {
filterStr = "(&" + objectClass + filterStr + ")";
} else {
filterStr = "(&" + objectClass + "(" + filterStr + ")" + ")";
}
}
FilterId filterId = options.getFilterId();
if (filterId == null) {
throw ServiceException.INVALID_REQUEST("missing filter id", null);
}
filter = filterFactory.fromFilterString(options.getFilterId(), filterStr);
}
if (domain != null && !InMemoryLdapServer.isOn()) {
boolean groupsTree = false;
boolean peopleTree = false;
if (types.contains(ObjectType.dynamicgroups)) {
groupsTree = true;
}
if (types.contains(ObjectType.accounts) ||
types.contains(ObjectType.aliases) ||
types.contains(ObjectType.distributionlists) ||
types.contains(ObjectType.resources)) {
peopleTree = true;
}
if (groupsTree && peopleTree) {
ZLdapFilter dnSubtreeMatchFilter = ((LdapDomain) domain).getDnSubtreeMatchFilter();
filter = filterFactory.andWith(filter, dnSubtreeMatchFilter);
}
}
/*
* return attrs
*/
String[] returnAttrs = fixReturnAttrs(options.getReturnAttrs(), flags);
return searchObjects(bases, filter, returnAttrs, options, visitor);
}
private static String getObjectClassQuery(int flags) {
boolean accounts = (flags & Provisioning.SD_ACCOUNT_FLAG) != 0;
boolean aliases = (flags & Provisioning.SD_ALIAS_FLAG) != 0;
boolean lists = (flags & Provisioning.SD_DISTRIBUTION_LIST_FLAG) != 0;
boolean groups = (flags & Provisioning.SD_DYNAMIC_GROUP_FLAG) != 0;
boolean calendarResources = (flags & Provisioning.SD_CALENDAR_RESOURCE_FLAG) != 0;
boolean domains = (flags & Provisioning.SD_DOMAIN_FLAG) != 0;
boolean coses = (flags & Provisioning.SD_COS_FLAG) != 0;
int num = (accounts ? 1 : 0) +
(aliases ? 1 : 0) +
(lists ? 1 : 0) +
(groups ? 1 : 0) +
(domains ? 1 : 0) +
(coses ? 1 : 0) +
(calendarResources ? 1 : 0);
if (num == 0) {
accounts = true;
}
// If searching for user accounts/aliases/lists, filter looks like:
//
// (&(objectclass=zimbraAccount)!(objectclass=zimbraCalendarResource))
//
// If searching for calendar resources, filter looks like:
//
// (objectclass=zimbraCalendarResource)
//
// The !resource condition is there in first case because a calendar
// resource is also a zimbraAccount.
//
StringBuffer oc = new StringBuffer();
if (accounts && !calendarResources) {
oc.append("(&");
}
if (num > 1) {
oc.append("(|");
}
if (accounts) oc.append("(objectclass=zimbraAccount)");
if (aliases) oc.append("(objectclass=zimbraAlias)");
if (lists) oc.append("(objectclass=zimbraDistributionList)");
if (groups) oc.append("(objectclass=zimbraGroup)");
if (domains) oc.append("(objectclass=zimbraDomain)");
if (coses) oc.append("(objectclass=zimbraCos)");
if (calendarResources) oc.append("(objectclass=zimbraCalendarResource)");
if (num > 1) {
oc.append(")");
}
if (accounts && !calendarResources) {
oc.append("(!(objectclass=zimbraCalendarResource)))");
}
return oc.toString();
}
private static class NamedEntryComparator implements Comparator<NamedEntry> {
final Provisioning mProv;
final String mSortAttr;
final boolean mSortAscending;
final boolean mByName;
NamedEntryComparator(Provisioning prov, String sortAttr, boolean sortAscending) {
mProv = prov;
mSortAttr = sortAttr;
mSortAscending = sortAscending;
mByName = sortAttr == null || sortAttr.length() == 0 || sortAttr.equals("name");
}
@Override
public int compare(NamedEntry a, NamedEntry b) {
int comp = 0;
if (mByName)
comp = a.getName().compareToIgnoreCase(b.getName());
else {
String sa = null;
String sb = null;
if (SearchDirectoryOptions.SORT_BY_TARGET_NAME.equals(mSortAttr) &&
(a instanceof Alias) && (b instanceof Alias)) {
try {
sa = ((Alias)a).getTargetUnicodeName(mProv);
} catch (ServiceException e) {
ZimbraLog.account.error("unable to get target name: "+a.getName(), e);
}
try {
sb = ((Alias)b).getTargetUnicodeName(mProv);
} catch (ServiceException e) {
ZimbraLog.account.error("unable to get target name: "+b.getName(), e);
}
} else {
sa = a.getAttr(mSortAttr);
sb = b.getAttr(mSortAttr);
}
if (sa == null) sa = "";
if (sb == null) sb = "";
comp = sa.compareToIgnoreCase(sb);
}
return mSortAscending ? comp : -comp;
}
};
@TODO
private static class SearchObjectsVisitor extends SearchLdapVisitor {
private LdapProvisioning prov;
private ZLdapContext zlc;
private String configBranchBaseDn;
private NamedEntry.Visitor visitor;
private int maxResults;
private MakeObjectOpt makeObjOpt;
private String returnAttrs[];
private int total = 0;
private SearchObjectsVisitor(LdapProvisioning prov, ZLdapContext zlc,
NamedEntry.Visitor visitor, int maxResults, MakeObjectOpt makeObjOpt,
String returnAttrs[]) {
super(false);
this.prov = prov;
this.zlc = zlc;
configBranchBaseDn = prov.getDIT().configBranchBaseDN();
this.visitor = visitor;
this.maxResults = maxResults;
this.makeObjOpt = makeObjOpt;
this.returnAttrs = returnAttrs;
}
@Override
public void visit(String dn, IAttributes ldapAttrs) {
try {
doVisit(dn, ldapAttrs);
} catch (ServiceException e) {
ZimbraLog.account.warn("entry skipped, encountered error while processing entry at:" + dn, e);
}
}
@TODO
private void doVisit(String dn, IAttributes ldapAttrs) throws ServiceException {
/* can this happen? TODO: check
if (maxResults > 0 && total++ > maxResults) {
throw AccountServiceException.TOO_MANY_SEARCH_RESULTS("exceeded limit of "+maxResults, null);
}
*/
List<String> objectclass =
ldapAttrs.getMultiAttrStringAsList(Provisioning.A_objectClass, CheckBinary.NOCHECK);
// skip admin accounts
// if we are looking for domains or coses, they can be under config branch in non default DIT impl.
if (dn.endsWith(configBranchBaseDn) &&
!objectclass.contains(AttributeClass.OC_zimbraDomain) &&
!objectclass.contains(AttributeClass.OC_zimbraCOS)) {
return;
}
ZAttributes attrs = (ZAttributes)ldapAttrs;
if (objectclass == null || objectclass.contains(AttributeClass.OC_zimbraAccount)) {
visitor.visit(prov.makeAccount(dn, attrs, makeObjOpt));
} else if (objectclass.contains(AttributeClass.OC_zimbraAlias)) {
visitor.visit(prov.makeAlias(dn, attrs));
} else if (objectclass.contains(AttributeClass.OC_zimbraDistributionList)) {
boolean isBasic = returnAttrs != null;
visitor.visit(prov.makeDistributionList(dn, attrs, isBasic));
} else if (objectclass.contains(AttributeClass.OC_zimbraGroup)) {
visitor.visit(prov.makeDynamicGroup(zlc, dn, attrs));
} else if (objectclass.contains(AttributeClass.OC_zimbraDomain)) {
visitor.visit(new LdapDomain(dn, attrs, prov.getConfig().getDomainDefaults(), prov));
} else if (objectclass.contains(AttributeClass.OC_zimbraCOS)) {
visitor.visit(new LdapCos(dn, attrs, prov));
}
}
}
/**
*
* @param base
* @param filter
* @param returnAttrs
* @param opts
* @param visitor
* @return null if visitor is not null, List<NamedEntry> if visitor is null
* @throws ServiceException
*/
private List<NamedEntry> searchObjects(String[] bases, ZLdapFilter filter, String returnAttrs[],
SearchDirectoryOptions opts, NamedEntry.Visitor visitor)
throws ServiceException {
if (visitor != null) {
if (opts.getSortOpt() != SortOpt.NO_SORT) {
throw ServiceException.INVALID_REQUEST("Sorting is not supported with visitor interface", null);
}
for (String base : bases) {
searchLdapObjects(base, filter, returnAttrs, opts, visitor);
}
return null;
} else {
final List<NamedEntry> result = new ArrayList<NamedEntry>();
NamedEntry.Visitor listBackedVisitor = new NamedEntry.Visitor() {
@Override
public void visit(NamedEntry entry) {
result.add(entry);
}
};
for (String base : bases) {
searchLdapObjects(base, filter, returnAttrs, opts, listBackedVisitor);
}
if (opts.getSortOpt() == SortOpt.NO_SORT) {
return result;
} else {
NamedEntryComparator comparator =
new NamedEntryComparator(this,
opts.getSortAttr(), opts.getSortOpt()==SortOpt.SORT_ASCENDING);
Collections.sort(result, comparator);
return result;
}
}
}
private void searchLdapObjects(String base, ZLdapFilter filter, String returnAttrs[],
SearchDirectoryOptions opts, NamedEntry.Visitor visitor)
throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.get(opts.getOnMaster()), opts.getUseConnPool(), LdapUsage.SEARCH);
SearchObjectsVisitor searchObjectsVisitor =
new SearchObjectsVisitor(this, zlc, visitor, opts.getMaxResults(),
opts.getMakeObjectOpt(), returnAttrs);
SearchLdapOptions searchObjectsOptions = new SearchLdapOptions(base, filter,
returnAttrs, opts.getMaxResults(), null, ZSearchScope.SEARCH_SCOPE_SUBTREE,
searchObjectsVisitor);
zlc.searchPaged(searchObjectsOptions);
} catch (LdapSizeLimitExceededException e) {
throw AccountServiceException.TOO_MANY_SEARCH_RESULTS("too many search results returned", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all objects", e);
} finally {
LdapClient.closeContext(zlc);
}
}
/*
* add required attrs to list of return attrs if not specified,
* since we need them to construct an Entry
*
* TODO: return flags and use a cleaner API
*/
private String[] fixReturnAttrs(String[] returnAttrs, int flags) {
if (returnAttrs == null || returnAttrs.length == 0)
return null;
boolean needUID = true;
boolean needID = true;
boolean needCOSId = true;
boolean needObjectClass = true;
boolean needAliasTargetId = (flags & Provisioning.SD_ALIAS_FLAG) != 0;
boolean needCalendarUserType = (flags & Provisioning.SD_CALENDAR_RESOURCE_FLAG) != 0;
boolean needDomainName = true;
boolean needZimbraACE = true;
boolean needCn = ((flags & Provisioning.SD_COS_FLAG) != 0) || ((flags & Provisioning.SD_DYNAMIC_GROUP_FLAG) != 0);
boolean needIsExternalVirtualAccount = (flags & Provisioning.SD_ACCOUNT_FLAG) != 0;
boolean needExternalUserMailAddress = (flags & Provisioning.SD_ACCOUNT_FLAG) != 0;
for (int i=0; i < returnAttrs.length; i++) {
if (Provisioning.A_uid.equalsIgnoreCase(returnAttrs[i]))
needUID = false;
else if (Provisioning.A_zimbraId.equalsIgnoreCase(returnAttrs[i]))
needID = false;
else if (Provisioning.A_zimbraCOSId.equalsIgnoreCase(returnAttrs[i]))
needCOSId = false;
else if (Provisioning.A_zimbraAliasTargetId.equalsIgnoreCase(returnAttrs[i]))
needAliasTargetId = false;
else if (Provisioning.A_objectClass.equalsIgnoreCase(returnAttrs[i]))
needObjectClass = false;
else if (Provisioning.A_zimbraAccountCalendarUserType.equalsIgnoreCase(returnAttrs[i]))
needCalendarUserType = false;
else if (Provisioning.A_zimbraDomainName.equalsIgnoreCase(returnAttrs[i]))
needDomainName = false;
else if (Provisioning.A_zimbraACE.equalsIgnoreCase(returnAttrs[i]))
needZimbraACE = false;
else if (Provisioning.A_cn.equalsIgnoreCase(returnAttrs[i]))
needCn = false;
else if (Provisioning.A_zimbraIsExternalVirtualAccount.equalsIgnoreCase(returnAttrs[i]))
needIsExternalVirtualAccount = false;
else if (Provisioning.A_zimbraExternalUserMailAddress.equalsIgnoreCase(returnAttrs[i]))
needExternalUserMailAddress = false;
}
int num = (needUID ? 1 : 0) +
(needID ? 1 : 0) +
(needCOSId ? 1 : 0) +
(needAliasTargetId ? 1 : 0) +
(needObjectClass ? 1 :0) +
(needCalendarUserType ? 1 : 0) +
(needDomainName ? 1 : 0) +
(needZimbraACE ? 1 : 0) +
(needCn ? 1 : 0) +
(needIsExternalVirtualAccount ? 1 : 0) +
(needExternalUserMailAddress ? 1 : 0);
if (num == 0) return returnAttrs;
String[] result = new String[returnAttrs.length+num];
int i = 0;
if (needUID) result[i++] = Provisioning.A_uid;
if (needID) result[i++] = Provisioning.A_zimbraId;
if (needCOSId) result[i++] = Provisioning.A_zimbraCOSId;
if (needAliasTargetId) result[i++] = Provisioning.A_zimbraAliasTargetId;
if (needObjectClass) result[i++] = Provisioning.A_objectClass;
if (needCalendarUserType) result[i++] = Provisioning.A_zimbraAccountCalendarUserType;
if (needDomainName) result[i++] = Provisioning.A_zimbraDomainName;
if (needZimbraACE) result[i++] = Provisioning.A_zimbraACE;
if (needCn) result[i++] = Provisioning.A_cn;
if (needIsExternalVirtualAccount) result[i++] = Provisioning.A_zimbraIsExternalVirtualAccount;
if (needExternalUserMailAddress) result[i++] = Provisioning.A_zimbraExternalUserMailAddress;
System.arraycopy(returnAttrs, 0, result, i, returnAttrs.length);
return result;
}
@Override
public void setCOS(Account acct, Cos cos) throws ServiceException {
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put(Provisioning.A_zimbraCOSId, cos.getId());
modifyAttrs(acct, attrs);
}
@Override
public void modifyAccountStatus(Account acct, String newStatus) throws ServiceException {
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put(Provisioning.A_zimbraAccountStatus, newStatus);
modifyAttrs(acct, attrs);
}
static String[] addMultiValue(String values[], String value) {
List<String> list = new ArrayList<String>(Arrays.asList(values));
list.add(value);
return list.toArray(new String[list.size()]);
}
String[] addMultiValue(NamedEntry acct, String attr, String value) {
return addMultiValue(acct.getMultiAttr(attr), value);
}
@Override
public void addAlias(Account acct, String alias) throws ServiceException {
addAliasInternal(acct, alias);
}
@Override
public void removeAlias(Account acct, String alias) throws ServiceException {
accountCache.remove(acct);
removeAliasInternal(acct, alias);
}
@Override
public void addAlias(DistributionList dl, String alias) throws ServiceException {
addAliasInternal(dl, alias);
allDLs.addGroup(dl);
}
@Override
public void removeAlias(DistributionList dl, String alias) throws ServiceException {
groupCache.remove(dl);
removeAliasInternal(dl, alias);
allDLs.removeGroup(alias);
}
private boolean isEntryAlias(ZAttributes attrs) throws ServiceException {
Map<String, Object> entryAttrs = attrs.getAttrs();
Object ocs = entryAttrs.get(Provisioning.A_objectClass);
if (ocs instanceof String)
return ((String)ocs).equalsIgnoreCase(AttributeClass.OC_zimbraAlias);
else if (ocs instanceof String[]) {
for (String oc : (String[])ocs) {
if (oc.equalsIgnoreCase(AttributeClass.OC_zimbraAlias))
return true;
}
}
return false;
}
private void addAliasInternal(NamedEntry entry, String alias) throws ServiceException {
LdapUsage ldapUsage = null;
String targetDomainName = null;
AliasedEntry aliasedEntry = null;
if (entry instanceof Account) {
aliasedEntry = (AliasedEntry)entry;
targetDomainName = ((Account)entry).getDomainName();
ldapUsage = LdapUsage.ADD_ALIAS_ACCOUNT;
} else if (entry instanceof Group) {
aliasedEntry = (AliasedEntry)entry;
ldapUsage = LdapUsage.ADD_ALIAS_DL;
targetDomainName = ((Group)entry).getDomainName();
} else {
throw ServiceException.FAILURE("invalid entry type for alias", null);
}
alias = alias.toLowerCase().trim();
alias = IDNUtil.toAsciiEmail(alias);
validEmailAddress(alias);
String parts[] = alias.split("@");
String aliasName = parts[0];
String aliasDomain = parts[1];
ZLdapContext zlc = null;
String aliasDn = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, ldapUsage);
Domain domain = getDomainByAsciiName(aliasDomain, zlc);
if (domain == null)
throw AccountServiceException.NO_SUCH_DOMAIN(aliasDomain);
aliasDn = mDIT.aliasDN(((LdapEntry)entry).getDN(), targetDomainName, aliasName, aliasDomain);
// the create and addAttr ideally would be in the same transaction
String aliasUuid = LdapUtil.generateUUID();
String targetEntryId = entry.getId();
try {
zlc.createEntry(aliasDn, "zimbraAlias",
new String[] { Provisioning.A_uid, aliasName,
Provisioning.A_zimbraId, aliasUuid,
Provisioning.A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()),
Provisioning.A_zimbraAliasTargetId, targetEntryId} );
} catch (LdapEntryAlreadyExistException e) {
/*
* check if the alias is a dangling alias. If so remove the dangling alias
* and create a new one.
*/
ZAttributes attrs = helper.getAttributes(zlc, aliasDn);
// see if the entry is an alias
if (!isEntryAlias(attrs))
throw e;
Alias aliasEntry = makeAlias(aliasDn, attrs);
NamedEntry targetEntry = searchAliasTarget(aliasEntry, false);
if (targetEntry == null) {
// remove the dangling alias
try {
removeAliasInternal(null, alias);
} catch (ServiceException se) {
// ignore
}
// try creating the alias again
zlc.createEntry(aliasDn, "zimbraAlias",
new String[] {
Provisioning.A_uid, aliasName,
Provisioning.A_zimbraId, aliasUuid,
Provisioning.A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()),
Provisioning.A_zimbraAliasTargetId, targetEntryId} );
} else if (targetEntryId.equals(targetEntry.getId())) {
// the alias target points to this account/DL
Set<String> mailAliases = entry.getMultiAttrSet(Provisioning.A_zimbraMailAlias);
Set<String> mails = entry.getMultiAttrSet(Provisioning.A_mail);
if (mailAliases != null && mailAliases.contains(alias) &&
mails != null && mails.contains(alias)) {
throw e;
} else {
ZimbraLog.account.warn("alias entry exists at " + aliasDn +
", but either mail or zimbraMailAlias of the target does not contain " +
alias + ", adding " + alias + " to entry " + entry.getName());
}
} else {
// not dangling, neither is the target the same entry as the account/DL
// for which the alias is being added for, rethrow the naming exception
throw e;
}
}
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("+" + Provisioning.A_zimbraMailAlias, alias);
attrs.put("+" + Provisioning.A_mail, alias);
// UGH
modifyAttrsInternal(entry, zlc, attrs);
removeExternalAddrsFromAllDynamicGroups(aliasedEntry.getAllAddrsSet(), zlc);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.ACCOUNT_EXISTS(alias, aliasDn, nabe);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create alias: "+e.getMessage(), e);
} finally {
LdapClient.closeContext(zlc);
}
}
/*
* 1. remove alias from mail and zimbraMailAlias attributes of the entry
* 2. remove alias from all distribution lists
* 3. delete the alias entry
*
* A. entry exists, alias exists
* - if alias points to the entry: do 1, 2, 3
* - if alias points to other existing entry: do 1, and then throw NO_SUCH_ALIAS
* - if alias points to a non-existing entry: do 1, 2, 3, and then throw NO_SUCH_ALIAS
*
* B. entry exists, alias does not exist: do 1, 2, and then throw NO_SUCH_ALIAS
*
* C. entry does not exist, alias exists:
* - if alias points to other existing entry: do nothing (and then throw NO_SUCH_ACCOUNT/NO_SUCH_DISTRIBUTION_LIST in ProvUtil)
* - if alias points to a non-existing entry: do 2, 3 (and then throw NO_SUCH_ACCOUNT/NO_SUCH_DISTRIBUTION_LIST in ProvUtil)
*
* D. entry does not exist, alias does not exist: do 2 (and then throw NO_SUCH_ACCOUNT/NO_SUCH_DISTRIBUTION_LIST in ProvUtil)
*
*
*/
private void removeAliasInternal(NamedEntry entry, String alias) throws ServiceException {
LdapUsage ldapUsage = null;
if (entry instanceof Account) {
ldapUsage = LdapUsage.REMOVE_ALIAS_ACCOUNT;
} else if (entry instanceof Group) {
ldapUsage = LdapUsage.REMOVE_ALIAS_DL;
} else {
ldapUsage = LdapUsage.REMOVE_ALIAS;
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, ldapUsage);
alias = alias.toLowerCase();
alias = IDNUtil.toAsciiEmail(alias);
String parts[] = alias.split("@");
String aliasName = parts[0];
String aliasDomain = parts[1];
Domain domain = getDomainByAsciiName(aliasDomain, zlc);
if (domain == null)
throw AccountServiceException.NO_SUCH_DOMAIN(aliasDomain);
String targetDn = (entry == null)?null:((LdapEntry)entry).getDN();
String targetDomainName = null;
if (entry != null) {
if (entry instanceof Account) {
targetDomainName = ((Account)entry).getDomainName();
} else if (entry instanceof Group) {
targetDomainName = ((Group)entry).getDomainName();
} else {
throw ServiceException.INVALID_REQUEST("invalid entry type for alias", null);
}
}
String aliasDn = mDIT.aliasDN(targetDn, targetDomainName, aliasName, aliasDomain);
ZAttributes aliasAttrs = null;
Alias aliasEntry = null;
try {
aliasAttrs = helper.getAttributes(zlc, aliasDn);
// see if the entry is an alias
if (!isEntryAlias(aliasAttrs))
throw AccountServiceException.NO_SUCH_ALIAS(alias);
aliasEntry = makeAlias(aliasDn, aliasAttrs);
} catch (ServiceException e) {
ZimbraLog.account.warn("alias " + alias + " does not exist");
}
NamedEntry targetEntry = null;
if (aliasEntry != null)
targetEntry = searchAliasTarget(aliasEntry, false);
boolean aliasPointsToEntry = ((entry != null) && (aliasEntry != null) &&
entry.getId().equals(aliasEntry.getAttr(Provisioning.A_zimbraAliasTargetId)));
boolean aliasPointsToOtherExistingEntry = ((aliasEntry != null) && (targetEntry != null) &&
((entry == null) || (!entry.getId().equals(targetEntry.getId()))));
boolean aliasPointsToNonExistingEntry = ((aliasEntry != null) && (targetEntry == null));
// 1. remove alias from mail/zimbraMailAlias attrs
if (entry != null) {
try {
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("-" + Provisioning.A_mail, alias);
attrs.put("-" + Provisioning.A_zimbraMailAlias, alias);
modifyAttrsInternal(entry, zlc, attrs);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to remove zimbraMailAlias/mail attrs: "+alias);
}
}
// 2. remove address from all DLs
if (!aliasPointsToOtherExistingEntry) {
removeAddressFromAllDistributionLists(alias);
}
// 3. remove the alias entry
if (aliasPointsToEntry || aliasPointsToNonExistingEntry) {
try {
zlc.deleteEntry(aliasDn);
} catch (ServiceException e) {
// should not happen, log it
ZimbraLog.account.warn("unable to remove alias entry at : " + aliasDn);
}
}
// throw NO_SUCH_ALIAS if necessary
if (((entry != null) && (aliasEntry == null)) ||
((entry != null) && (aliasEntry != null) && !aliasPointsToEntry))
throw AccountServiceException.NO_SUCH_ALIAS(alias);
} finally {
LdapClient.closeContext(zlc);
}
}
/**
* search alias target - implementation can return cached entry
*
* @param alias
* @param mustFind
* @return
* @throws ServiceException
*/
@Override
public NamedEntry getAliasTarget(Alias alias, boolean mustFind) throws ServiceException {
String targetId = alias.getAttr(Provisioning.A_zimbraAliasTargetId);
NamedEntry target;
// see it's an account/cr
target = get(AccountBy.id, targetId);
if (target != null)
return target;
// see if it's a group
target = getGroupBasic(Key.DistributionListBy.id, targetId);
return target;
}
@Override
public Domain createDomain(String name, Map<String, Object> domainAttrs)
throws ServiceException {
name = name.toLowerCase().trim();
name = IDNUtil.toAsciiDomainName(name);
NameUtil.validNewDomainName(name);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_DOMAIN);
LdapDomain d = (LdapDomain) getDomainByAsciiName(name, zlc);
if (d != null) {
throw AccountServiceException.DOMAIN_EXISTS(name);
}
// Attribute checking can not express "allow setting on
// creation, but do not allow modifies afterwards"
String domainType = (String) domainAttrs.get(A_zimbraDomainType);
if (domainType == null) {
domainType = DomainType.local.name();
} else {
domainAttrs.remove(A_zimbraDomainType); // add back later
}
String domainStatus = (String) domainAttrs.get(A_zimbraDomainStatus);
if (domainStatus == null) {
domainStatus = DOMAIN_STATUS_ACTIVE;
} else {
domainAttrs.remove(A_zimbraDomainStatus); // add back later
}
String smimeLdapURL = (String) domainAttrs.get(A_zimbraSMIMELdapURL);
if (!StringUtil.isNullOrEmpty(smimeLdapURL)) {
domainAttrs.remove(A_zimbraSMIMELdapURL); // add back later
}
String smimeLdapStartTlsEnabled = (String) domainAttrs.get(A_zimbraSMIMELdapStartTlsEnabled);
if (!StringUtil.isNullOrEmpty(smimeLdapStartTlsEnabled)) {
domainAttrs.remove(A_zimbraSMIMELdapStartTlsEnabled); // add back later
}
String smimeLdapBindDn = (String) domainAttrs.get(A_zimbraSMIMELdapBindDn);
if (!StringUtil.isNullOrEmpty(smimeLdapBindDn)) {
domainAttrs.remove(A_zimbraSMIMELdapBindDn); // add back later
}
String smimeLdapBindPassword = (String) domainAttrs.get(A_zimbraSMIMELdapBindPassword);
if (!StringUtil.isNullOrEmpty(smimeLdapBindPassword)) {
domainAttrs.remove(A_zimbraSMIMELdapBindPassword); // add back later
}
String smimeLdapSearchBase = (String) domainAttrs.get(A_zimbraSMIMELdapSearchBase);
if (!StringUtil.isNullOrEmpty(smimeLdapSearchBase)) {
domainAttrs.remove(A_zimbraSMIMELdapSearchBase); // add back later
}
String smimeLdapFilter = (String) domainAttrs.get(A_zimbraSMIMELdapFilter);
if (!StringUtil.isNullOrEmpty(smimeLdapFilter)) {
domainAttrs.remove(A_zimbraSMIMELdapFilter); // add back later
}
String smimeLdapAttribute = (String) domainAttrs.get(A_zimbraSMIMELdapAttribute);
if (!StringUtil.isNullOrEmpty(smimeLdapAttribute)) {
domainAttrs.remove(A_zimbraSMIMELdapAttribute); // add back later
}
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(domainAttrs, null, callbackContext, true);
// Add back attrs we circumvented from attribute checking
domainAttrs.put(A_zimbraDomainType, domainType);
domainAttrs.put(A_zimbraDomainStatus, domainStatus);
domainAttrs.put(A_zimbraSMIMELdapURL, smimeLdapURL);
domainAttrs.put(A_zimbraSMIMELdapStartTlsEnabled, smimeLdapStartTlsEnabled);
domainAttrs.put(A_zimbraSMIMELdapBindDn, smimeLdapBindDn);
domainAttrs.put(A_zimbraSMIMELdapBindPassword, smimeLdapBindPassword);
domainAttrs.put(A_zimbraSMIMELdapSearchBase, smimeLdapSearchBase);
domainAttrs.put(A_zimbraSMIMELdapFilter, smimeLdapFilter);
domainAttrs.put(A_zimbraSMIMELdapAttribute, smimeLdapAttribute);
String parts[] = name.split("\\.");
String dns[] = mDIT.domainToDNs(parts);
createParentDomains(zlc, parts, dns);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(domainAttrs);
Set<String> ocs = LdapObjectClass.getDomainObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_zimbraDomainName, name);
String mailStatus = (String) domainAttrs.get(A_zimbraMailStatus);
if (mailStatus == null)
entry.setAttr(A_zimbraMailStatus, MAIL_STATUS_ENABLED);
if (domainType.equalsIgnoreCase(DomainType.alias.name())) {
entry.setAttr(A_zimbraMailCatchAllAddress, "@" + name);
}
entry.setAttr(A_o, name+" domain");
entry.setAttr(A_dc, parts[0]);
String dn = dns[0];
entry.setDN(dn);
//NOTE: all four of these should be in a transaction...
try {
zlc.createEntry(entry);
} catch (LdapEntryAlreadyExistException e) {
zlc.replaceAttributes(dn, entry.getAttributes());
}
String acctBaseDn = mDIT.domainDNToAccountBaseDN(dn);
if (!acctBaseDn.equals(dn)) {
/*
* create the account base dn entry only if if is not the same as the domain dn
*
* TODO, the objectclass(organizationalRole) and attrs(ou and cn) for the account
* base dn entry is still hardcoded, it should be parameterized in LdapDIT
* according the BASE_RDN_ACCOUNT. This is actually a design decision depending
* on how far we want to allow the DIT to be customized.
*/
zlc.createEntry(mDIT.domainDNToAccountBaseDN(dn),
"organizationalRole",
new String[] { A_ou, "people", A_cn, "people"});
// create the base DN for dynamic groups
zlc.createEntry(mDIT.domainDNToDynamicGroupsBaseDN(dn),
"organizationalRole",
new String[] { A_cn, "groups", A_description, "dynamic groups base"});
}
Domain domain = getDomainById(zimbraIdStr, zlc);
AttributeManager.getInstance().postModify(domainAttrs, domain, callbackContext);
return domain;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DOMAIN_EXISTS(name);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create domain: "+name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
private LdapDomain getDomainByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.domainBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapDomain(sr.getDN(), sr.getAttributes(), getConfig().getDomainDefaults(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_DOMAINS_MATCHED("getDomainByQuery: " + e.getMessage());
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup domain via query: " +
filter.toFilterString() + " message:"+e.getMessage(), e);
}
return null;
}
@Override
public Domain get(Key.DomainBy keyType, String key) throws ServiceException {
return getDomain(keyType, key, false);
}
@Override
public Domain getDomain(Key.DomainBy keyType, String key, boolean checkNegativeCache)
throws ServiceException {
// note: *always* use negative cache for keys from external source
// - virtualHostname, foreignName, krb5Realm
GetFromDomainCacheOption option = checkNegativeCache ?
GetFromDomainCacheOption.BOTH : GetFromDomainCacheOption.POSITIVE;
switch(keyType) {
case name:
return getDomainByNameInternal(key, option);
case id:
return getDomainByIdInternal(key, null, option);
case virtualHostname:
return getDomainByVirtualHostnameInternal(key, GetFromDomainCacheOption.BOTH);
case foreignName:
return getDomainByForeignNameInternal(key, GetFromDomainCacheOption.BOTH);
case krb5Realm:
return getDomainByKrb5RealmInternal(key, GetFromDomainCacheOption.BOTH);
default:
return null;
}
}
private Domain getFromCache(Key.DomainBy keyType, String key, GetFromDomainCacheOption option) {
switch(keyType) {
case name:
String asciiName = IDNUtil.toAsciiDomainName(key);
return domainCache.getByName(asciiName, option);
case id:
return domainCache.getById(key, option);
case virtualHostname:
return domainCache.getByVirtualHostname(key, option);
case krb5Realm:
return domainCache.getByKrb5Realm(key, option);
default:
return null;
}
}
private Domain getDomainById(String zimbraId, ZLdapContext zlc) throws ServiceException {
return getDomainByIdInternal(zimbraId, zlc, GetFromDomainCacheOption.POSITIVE);
}
private Domain getDomainByIdInternal(String zimbraId, ZLdapContext zlc,
GetFromDomainCacheOption option)
throws ServiceException {
if (zimbraId == null)
return null;
Domain d = domainCache.getById(zimbraId, option);
if (d instanceof DomainCache.NonExistingDomain)
return null;
LdapDomain domain = (LdapDomain)d;
if (domain == null) {
domain = getDomainByQuery(filterFactory.domainById(zimbraId), zlc);
domainCache.put(Key.DomainBy.id, zimbraId, domain);
}
return domain;
}
private Domain getDomainByNameInternal(String name, GetFromDomainCacheOption option)
throws ServiceException {
String asciiName = IDNUtil.toAsciiDomainName(name);
return getDomainByAsciiNameInternal(asciiName, null, option);
}
private Domain getDomainByAsciiName(String name, ZLdapContext zlc)
throws ServiceException {
return getDomainByAsciiNameInternal(name, zlc, GetFromDomainCacheOption.POSITIVE);
}
private Domain getDomainByAsciiNameInternal(String name, ZLdapContext zlc,
GetFromDomainCacheOption option)
throws ServiceException {
Domain d = domainCache.getByName(name, option);
if (d instanceof DomainCache.NonExistingDomain)
return null;
LdapDomain domain = (LdapDomain)d;
if (domain == null) {
domain = getDomainByQuery(filterFactory.domainByName(name), zlc);
domainCache.put(Key.DomainBy.name, name, domain);
}
return domain;
}
private Domain getDomainByVirtualHostnameInternal(String virtualHostname,
GetFromDomainCacheOption option)
throws ServiceException {
Domain d = domainCache.getByVirtualHostname(virtualHostname, option);
if (d instanceof DomainCache.NonExistingDomain)
return null;
LdapDomain domain = (LdapDomain)d;
if (domain == null) {
domain = getDomainByQuery(filterFactory.domainByVirtualHostame(virtualHostname), null);
domainCache.put(Key.DomainBy.virtualHostname, virtualHostname, domain);
}
return domain;
}
private Domain getDomainByForeignNameInternal(String foreignName,
GetFromDomainCacheOption option)
throws ServiceException {
Domain d = domainCache.getByForeignName(foreignName, option);
if (d instanceof DomainCache.NonExistingDomain)
return null;
LdapDomain domain = (LdapDomain)d;
if (domain == null) {
domain = getDomainByQuery(filterFactory.domainByForeignName(foreignName), null);
domainCache.put(Key.DomainBy.foreignName, foreignName, domain);
}
return domain;
}
private Domain getDomainByKrb5RealmInternal(String krb5Realm,
GetFromDomainCacheOption option)
throws ServiceException {
Domain d = domainCache.getByKrb5Realm(krb5Realm, option);
if (d instanceof DomainCache.NonExistingDomain)
return null;
LdapDomain domain = (LdapDomain)d;
if (domain == null) {
domain = getDomainByQuery(filterFactory.domainByKrb5Realm(krb5Realm), null);
domainCache.put(Key.DomainBy.krb5Realm, krb5Realm, domain);
}
return domain;
}
@Override
public List<Domain> getAllDomains() throws ServiceException {
final List<Domain> result = new ArrayList<Domain>();
NamedEntry.Visitor visitor = new NamedEntry.Visitor() {
@Override
public void visit(NamedEntry entry) {
result.add((LdapDomain)entry);
}
};
getAllDomains(visitor, null);
Collections.sort(result);
return result;
}
@Override
public void getAllDomains(NamedEntry.Visitor visitor, String[] retAttrs)
throws ServiceException {
SearchDirectoryOptions opts = new SearchDirectoryOptions(retAttrs);
opts.setFilter(filterFactory.allDomains());
opts.setTypes(ObjectType.domains);
searchDirectoryInternal(opts, visitor);
}
private boolean domainDnExists(ZLdapContext zlc, String dn) throws ServiceException {
try {
ZSearchResultEnumeration ne = helper.searchDir(dn, filterFactory.domainLabel(),
ZSearchControls.SEARCH_CTLS_SUBTREE(), zlc, LdapServerType.MASTER);
boolean result = ne.hasMore();
ne.close();
return result;
} catch (ServiceException e) { // or should we throw? TODO
return false;
}
}
private void createParentDomains(ZLdapContext zlc, String parts[], String dns[])
throws ServiceException {
for (int i=dns.length-1; i > 0; i--) {
if (!domainDnExists(zlc, dns[i])) {
String dn = dns[i];
String domain = parts[i];
// don't create ZimbraDomain objects, since we don't want them to show up in list domains
zlc.createEntry(dn, new String[] {"dcObject", "organization"},
new String[] { A_o, domain+" domain", A_dc, domain });
}
}
}
@Override
public Cos createCos(String name, Map<String, Object> cosAttrs) throws ServiceException {
String defaultCosId = getCosByName(DEFAULT_COS_NAME, null).getId();
return copyCos(defaultCosId, name, cosAttrs);
}
@Override
public Cos copyCos(String srcCosId, String destCosName) throws ServiceException {
return copyCos(srcCosId, destCosName, null);
}
private Cos copyCos(String srcCosId, String destCosName, Map<String, Object> cosAttrs)
throws ServiceException {
destCosName = destCosName.toLowerCase().trim();
Cos srcCos = getCosById(srcCosId, null);
if (srcCos == null)
throw AccountServiceException.NO_SUCH_COS(srcCosId);
// bug 67716, use a case insensitive map because provided attr names may not be
// the canonical name and that will cause multiple entries in the map
Map<String, Object> allAttrs = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
allAttrs.putAll(srcCos.getAttrs());
allAttrs.remove(Provisioning.A_objectClass);
allAttrs.remove(Provisioning.A_zimbraId);
allAttrs.remove(Provisioning.A_zimbraCreateTimestamp);
allAttrs.remove(Provisioning.A_zimbraACE);
allAttrs.remove(Provisioning.A_cn);
allAttrs.remove(Provisioning.A_description);
if (cosAttrs != null) {
for (Map.Entry<String, Object> e : cosAttrs.entrySet()) {
String attr = e.getKey();
Object value = e.getValue();
if (value instanceof String && Strings.isNullOrEmpty((String)value)) {
allAttrs.remove(attr);
} else {
allAttrs.put(attr, value);
}
}
}
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
//get rid of deprecated attrs
Map<String, Object> allNewAttrs = new HashMap<String, Object>(allAttrs);
for (String attr : allAttrs.keySet()) {
AttributeInfo info = AttributeManager.getInstance().getAttributeInfo(attr);
if (info.isDeprecated()) {
allNewAttrs.remove(attr);
}
}
allAttrs = allNewAttrs;
AttributeManager.getInstance().preModify(allAttrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_COS);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(allAttrs);
Set<String> ocs = LdapObjectClass.getCosObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_cn, destCosName);
String dn = mDIT.cosNametoDN(destCosName);
entry.setDN(dn);
zlc.createEntry(entry);
Cos cos = getCosById(zimbraIdStr, zlc);
AttributeManager.getInstance().postModify(allAttrs, cos, callbackContext);
return cos;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.COS_EXISTS(destCosName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create cos: " + destCosName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void renameCos(String zimbraId, String newName) throws ServiceException {
LdapCos cos = (LdapCos) get(Key.CosBy.id, zimbraId);
if (cos == null)
throw AccountServiceException.NO_SUCH_COS(zimbraId);
if (cos.isDefaultCos())
throw ServiceException.INVALID_REQUEST("unable to rename default cos", null);
newName = newName.toLowerCase().trim();
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_COS);
String newDn = mDIT.cosNametoDN(newName);
zlc.renameEntry(cos.getDN(), newDn);
// remove old cos from cache
cosCache.remove(cos);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.COS_EXISTS(newName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename cos: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
private LdapCos getCOSByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.cosBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapCos(sr.getDN(), sr.getAttributes(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getCOSByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup cos via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private Cos getCosById(String zimbraId, ZLdapContext zlc) throws ServiceException {
if (zimbraId == null)
return null;
LdapCos cos = cosCache.getById(zimbraId);
if (cos == null) {
cos = getCOSByQuery(filterFactory.cosById(zimbraId), zlc);
cosCache.put(cos);
}
return cos;
}
@Override
public Cos get(Key.CosBy keyType, String key) throws ServiceException {
switch(keyType) {
case name:
return getCosByName(key, null);
case id:
return getCosById(key, null);
default:
return null;
}
}
private Cos getFromCache(Key.CosBy keyType, String key) {
switch(keyType) {
case name:
return cosCache.getByName(key);
case id:
return cosCache.getById(key);
default:
return null;
}
}
private Cos getCosByName(String name, ZLdapContext initZlc) throws ServiceException {
LdapCos cos = cosCache.getByName(name);
if (cos != null)
return cos;
try {
String dn = mDIT.cosNametoDN(name);
ZAttributes attrs = helper.getAttributes(
initZlc, LdapServerType.REPLICA, LdapUsage.GET_COS, dn, null);
cos = new LdapCos(dn, attrs, this);
cosCache.put(cos);
return cos;
} catch (LdapEntryNotFoundException e) {
return null;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup COS by name: " + name +
" message: "+e.getMessage(), e);
}
}
@Override
public List<Cos> getAllCos() throws ServiceException {
List<Cos> result = new ArrayList<Cos>();
try {
ZSearchResultEnumeration ne = helper.searchDir(mDIT.cosBaseDN(),
filterFactory.allCoses(), ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapCos(sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all COS", e);
}
Collections.sort(result);
return result;
}
@Override
public void deleteAccount(String zimbraId) throws ServiceException {
Account acc = getAccountById(zimbraId);
LdapEntry entry = (LdapEntry) getAccountById(zimbraId);
if (acc == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(zimbraId);
// remove the account from all DLs
removeAddressFromAllDistributionLists(acc.getName()); // this doesn't throw any exceptions
// delete all aliases of the account
String aliases[] = acc.getMailAlias();
if (aliases != null) {
for (int i=0; i < aliases.length; i++) {
try {
removeAlias(acc, aliases[i]); // this also removes each alias from any DLs
} catch (ServiceException se) {
if (AccountServiceException.NO_SUCH_ALIAS.equals(se.getCode())) {
ZimbraLog.account.warn("got no such alias from removeAlias call when deleting account; likely alias was previously in a bad state");
} else {
throw se;
}
}
}
}
// delete all grants granted to the account
try {
RightCommand.revokeAllRights(this, GranteeType.GT_USER, zimbraId);
} catch (ServiceException e) {
// eat the exception and continue
ZimbraLog.account.warn("cannot revoke grants", e);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_ACCOUNT);
zlc.deleteChildren(entry.getDN());
zlc.deleteEntry(entry.getDN());
accountCache.remove(acc);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge account: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void renameAccount(String zimbraId, String newName) throws ServiceException {
newName = IDNUtil.toAsciiEmail(newName);
validEmailAddress(newName);
ZLdapContext zlc = null;
Account acct = getAccountById(zimbraId, zlc, true);
// prune cache
accountCache.remove(acct);
LdapEntry entry = (LdapEntry) acct;
if (acct == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(zimbraId);
String oldEmail = acct.getName();
boolean domainChanged = false;
Account oldAccount = acct;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_ACCOUNT);
String oldDn = entry.getDN();
String[] parts = EmailUtil.getLocalPartAndDomain(oldEmail);
String oldLocal = parts[0];
String oldDomain = parts[1];
newName = newName.toLowerCase().trim();
parts = EmailUtil.getLocalPartAndDomain(newName);
if (parts == null) {
throw ServiceException.INVALID_REQUEST("bad value for newName", null);
}
String newLocal = parts[0];
String newDomain = parts[1];
Domain domain = getDomainByAsciiName(newDomain, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(newDomain);
}
domainChanged = !newDomain.equals(oldDomain);
if (domainChanged) {
validate(ProvisioningValidator.RENAME_ACCOUNT, newName, acct.getMultiAttr(Provisioning.A_objectClass, false), acct.getAttrs(false));
validate(ProvisioningValidator.RENAME_ACCOUNT_CHECK_DOMAIN_COS_AND_FEATURE, newName, acct.getAttrs(false));
// make sure the new domain is a local domain
if (!domain.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
}
String newDn = mDIT.accountDNRename(oldDn, newLocal, domain.getName());
boolean dnChanged = (!newDn.equals(oldDn));
Map<String,Object> newAttrs = acct.getAttrs(false);
if (dnChanged) {
// uid will be changed during renameEntry, so no need to modify it
// OpenLDAP is OK modifying it, as long as it matches the new DN, but
// InMemoryDirectoryServer does not like it.
newAttrs.remove(Provisioning.A_uid);
} else {
newAttrs.put(Provisioning.A_uid, newLocal);
}
newAttrs.put(Provisioning.A_zimbraMailDeliveryAddress, newName);
if (oldEmail.equals(newAttrs.get(
Provisioning.A_zimbraPrefFromAddress))) {
newAttrs.put(Provisioning.A_zimbraPrefFromAddress, newName);
}
ReplaceAddressResult replacedMails = replaceMailAddresses(
acct, Provisioning.A_mail, oldEmail, newName);
if (replacedMails.newAddrs().length == 0) {
// Set mail to newName if the account currently does not have a mail
newAttrs.put(Provisioning.A_mail, newName);
} else {
newAttrs.put(Provisioning.A_mail, replacedMails.newAddrs());
}
ReplaceAddressResult replacedAliases = replaceMailAddresses(
acct, Provisioning.A_zimbraMailAlias, oldEmail, newName);
if (replacedAliases.newAddrs().length > 0) {
newAttrs.put(Provisioning.A_zimbraMailAlias, replacedAliases.newAddrs());
String newDomainDN = mDIT.domainToAccountSearchDN(newDomain);
String[] aliasNewAddrs = replacedAliases.newAddrs();
// check up front if any of renamed aliases already exists in the new domain
// (if domain also got changed)
if (domainChanged && addressExistsUnderDN(zlc, newDomainDN, aliasNewAddrs)) {
throw AccountServiceException.ACCOUNT_EXISTS(newName);
}
// if any of the renamed aliases clashes with the account's new name,
// it won't be caught by the above check, do a separate check.
for (int i=0; i < aliasNewAddrs.length; i++) {
if (newName.equalsIgnoreCase(aliasNewAddrs[i])) {
throw AccountServiceException.ACCOUNT_EXISTS(newName);
}
}
}
ReplaceAddressResult replacedAllowAddrForDelegatedSender =
replaceMailAddresses(acct, Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
oldEmail, newName);
if (replacedAllowAddrForDelegatedSender.newAddrs().length > 0) {
newAttrs.put(Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
replacedAllowAddrForDelegatedSender.newAddrs());
}
if (newAttrs.get(Provisioning.A_displayName) == null && oldLocal.equals(newAttrs.get(Provisioning.A_cn)))
newAttrs.put(Provisioning.A_cn, newLocal);
/*
ZMutableEntry mutableEntry = LdapClient.createMutableEntry();
mutableEntry.mapToAttrs(newAttrs);
mutableEntry.setDN(newDn);
*/
if (dnChanged) {
zlc.renameEntry(oldDn, newDn);
// re-get the acct object, make sure we don't get it from cache
// Note: this account object contains the old address, it should never
// be cached
acct = getAccountByQuery(mDIT.mailBranchBaseDN(), filterFactory.accountById(zimbraId), zlc, true);
if (acct == null) {
throw ServiceException.FAILURE("cannot find account by id after modrdn", null);
}
}
// rename the account and all it's renamed aliases to the new name in all
// distribution lists. Doesn't throw exceptions, just logs
renameAddressesInAllDistributionLists(oldEmail, newName, replacedAliases);
// MOVE OVER ALL aliases
// doesn't throw exceptions, just logs
if (domainChanged) {
moveAliases(zlc, replacedAliases, newDomain, null, oldDn, newDn, oldDomain, newDomain);
}
modifyLdapAttrs(acct, zlc, newAttrs);
// re-get the account again, now attrs contains new addrs
acct = getAccountByQuery(mDIT.mailBranchBaseDN(), filterFactory.accountById(zimbraId), zlc, true);
if (acct == null) {
throw ServiceException.FAILURE("cannot find account by id after modrdn", null);
}
removeExternalAddrsFromAllDynamicGroups(acct.getAllAddrsSet(), zlc);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.ACCOUNT_EXISTS(newName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename account: "+newName, e);
} finally {
LdapClient.closeContext(zlc);
// prune cache
accountCache.remove(oldAccount);
}
// reload it to cache using the master, bug 45736
Account renamedAcct = getAccountById(zimbraId, null, true);
if (domainChanged) {
PermissionCache.invalidateCache(renamedAcct);
}
}
@Override
public void deleteDomain(String zimbraId) throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_DOMAIN);
Domain domain = getDomainById(zimbraId, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(zimbraId);
}
List<String> aliasDomainIds = null;
if (domain.isLocal()) {
aliasDomainIds = getEmptyAliasDomainIds(zlc, domain);
}
// delete the domain;
deleteDomainInternal(zlc, zimbraId);
// delete all alias domains if any
if (aliasDomainIds != null) {
for (String aliasDomainId : aliasDomainIds) {
deleteDomainInternal(zlc, aliasDomainId);
}
}
} catch (ServiceException e) {
throw e;
} finally {
LdapClient.closeContext(zlc);
}
}
private List<String> getEmptyAliasDomainIds(ZLdapContext zlc, Domain targetDomain)
throws ServiceException {
List<String> aliasDomainIds = new ArrayList<String>();
ZSearchResultEnumeration ne = null;
try {
ZSearchControls searchControls = ZSearchControls.createSearchControls(
ZSearchScope.SEARCH_SCOPE_SUBTREE, ZSearchControls.SIZE_UNLIMITED,
new String[]{Provisioning.A_zimbraId, Provisioning.A_zimbraDomainName});
ne = helper.searchDir(mDIT.domainBaseDN(), filterFactory.domainAliases(targetDomain.getId()),
searchControls, zlc, LdapServerType.MASTER);
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
String aliasDomainId = sr.getAttributes().getAttrString(Provisioning.A_zimbraId);
String aliasDomainName = sr.getAttributes().getAttrString(Provisioning.A_zimbraDomainName);
// make sure the alias domain is ready to be deleted
String aliasDomainDn = sr.getDN();
String acctBaseDn = mDIT.domainDNToAccountBaseDN(aliasDomainDn);
String dynGroupsBaseDn = mDIT.domainDNToDynamicGroupsBaseDN(aliasDomainDn);
if (hasSubordinates(zlc, acctBaseDn) || hasSubordinates(zlc, dynGroupsBaseDn)) {
throw ServiceException.FAILURE("alias domain " + aliasDomainName +
" of doamin " + targetDomain.getName() + " is not empty", null);
}
if (aliasDomainId != null) {
aliasDomainIds.add(aliasDomainId);
}
}
} finally {
ne.close();
}
return aliasDomainIds;
}
private boolean hasSubordinates(ZLdapContext zlc, String dn) throws ServiceException {
boolean hasSubordinates = false;
ZSearchResultEnumeration ne = null;
try {
ne = helper.searchDir(dn,
filterFactory.hasSubordinates(), ZSearchControls.SEARCH_CTLS_SUBTREE(),
zlc, LdapServerType.MASTER);
hasSubordinates = ne.hasMore();
} finally {
if (ne != null) {
ne.close();
}
}
return hasSubordinates;
}
public void deleteDomainInternal(ZLdapContext zlc, String zimbraId) throws ServiceException {
// TODO: should only allow a domain delete to succeed if there are no people
// if there aren't, we need to delete the people trees first, then delete the domain.
LdapDomain domain = null;
String acctBaseDn = null;
String dynGroupsBaseDn = null;
try {
domain = (LdapDomain) getDomainById(zimbraId, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(zimbraId);
}
String name = domain.getName();
// delete account base DN
acctBaseDn = mDIT.domainDNToAccountBaseDN(domain.getDN());
if (!acctBaseDn.equals(domain.getDN())) {
try {
zlc.deleteEntry(acctBaseDn);
} catch (LdapEntryNotFoundException e) {
ZimbraLog.account.info("entry %s not found", acctBaseDn);
}
}
// delete dynamic groups base DN
dynGroupsBaseDn = mDIT.domainDNToDynamicGroupsBaseDN(domain.getDN());
if (!dynGroupsBaseDn.equals(domain.getDN())) {
try {
zlc.deleteEntry(dynGroupsBaseDn);
} catch (LdapEntryNotFoundException e) {
ZimbraLog.account.info("entry %s not found", dynGroupsBaseDn);
}
}
try {
zlc.deleteEntry(domain.getDN());
domainCache.remove(domain);
} catch (LdapContextNotEmptyException e) {
// remove from cache before nuking all attrs
domainCache.remove(domain);
// assume subdomains exist and turn into plain dc object
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("-"+A_objectClass, "zimbraDomain");
// remove all zimbra attrs
for (String key : domain.getAttrs(false).keySet()) {
if (key.startsWith("zimbra"))
attrs.put(key, "");
}
// cannot invoke callback here. If another domain attr is added in a callback,
// e.g. zimbraDomainStatus would add zimbraMailStatus, then we will get a LDAP
// schema violation naming error(zimbraDomain is removed, thus there cannot be
// any zimbraAttrs left) and the modify will fail.
modifyAttrs(domain, attrs, false, false);
}
String defaultDomain = getConfig().getAttr(A_zimbraDefaultDomainName, null);
if (name.equalsIgnoreCase(defaultDomain)) {
try {
Map<String, String> attrs = new HashMap<String, String>();
attrs.put(A_zimbraDefaultDomainName, "");
modifyAttrs(getConfig(), attrs);
} catch (Exception e) {
ZimbraLog.account.warn("unable to remove config attr:"+A_zimbraDefaultDomainName, e);
}
}
} catch (LdapContextNotEmptyException e) {
// get a few entries to include in the error message
int maxEntriesToGet = 5;
final String doNotReportThisDN = acctBaseDn;
final StringBuilder sb = new StringBuilder();
sb.append(" (remaining entries: ");
SearchLdapOptions.SearchLdapVisitor visitor = new SearchLdapOptions.SearchLdapVisitor() {
@Override
public void visit(String dn, Map<String, Object> attrs, IAttributes ldapAttrs) {
if (!dn.equals(doNotReportThisDN)) {
sb.append("[" + dn + "] ");
}
}
};
SearchLdapOptions searchOptions = new SearchLdapOptions(
acctBaseDn, filterFactory.anyEntry(),
new String[]{Provisioning.A_objectClass}, maxEntriesToGet, null,
ZSearchScope.SEARCH_SCOPE_SUBTREE, visitor);
try {
zlc.searchPaged(searchOptions);
} catch (LdapSizeLimitExceededException lslee) {
// quietly ignore
} catch (ServiceException se) {
ZimbraLog.account.warn("unable to get sample entries in non-empty domain "
+ domain.getName() + " for reporting", se);
}
sb.append("...)");
throw AccountServiceException.DOMAIN_NOT_EMPTY(domain.getName() + sb.toString(), e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge domain: "+zimbraId, e);
}
}
@Override // LdapProv
public void renameDomain(String zimbraId, String newDomainName) throws ServiceException {
newDomainName = newDomainName.toLowerCase().trim();
newDomainName = IDNUtil.toAsciiDomainName(newDomainName);
NameUtil.validNewDomainName(newDomainName);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_DOMAIN);
RenameDomain.RenameDomainLdapHelper helper =
new RenameDomain.RenameDomainLdapHelper(this, zlc) {
private ZLdapContext toZLdapContext() {
return LdapClient.toZLdapContext(mProv, mZlc);
}
@Override
public void createEntry(String dn, Map<String, Object> attrs)
throws ServiceException {
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(attrs);
entry.setDN(dn);
ZLdapContext ldapContext = toZLdapContext();
ldapContext.createEntry(entry);
}
@Override
public void deleteEntry(String dn) throws ServiceException {
ZLdapContext ldapContext = toZLdapContext();
ldapContext.deleteEntry(dn);
}
@Override
public void renameEntry(String oldDn, String newDn)
throws ServiceException {
ZLdapContext ldapContext = toZLdapContext();
ldapContext.renameEntry(oldDn, newDn);
}
@Override
public void searchDirectory(SearchDirectoryOptions options,
NamedEntry.Visitor visitor) throws ServiceException {
((LdapProvisioning) mProv).searchDirectory(options, visitor);
}
@Override
public void renameAddressesInAllDistributionLists(Map<String, String> changedPairs) {
((LdapProvisioning) mProv).renameAddressesInAllDistributionLists(changedPairs);
}
@Override
public void renameXMPPComponent(String zimbraId, String newName)
throws ServiceException {
((LdapProvisioning) mProv).renameXMPPComponent(zimbraId, newName);
}
@Override
public Account getAccountById(String id) throws ServiceException {
// note: we do NOT want to get a cached entry
return ((LdapProvisioning) mProv).getAccountByQuery(
mProv.getDIT().mailBranchBaseDN(),
ZLdapFilterFactory.getInstance().accountById(id), toZLdapContext(), true);
}
@Override
public DistributionList getDistributionListById(String id)
throws ServiceException {
// note: we do NOT want to get a cahed entry
return ((LdapProvisioning) mProv).getDistributionListByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.distributionListById(id),
toZLdapContext(), false);
}
@Override
public DynamicGroup getDynamicGroupById(String id) throws ServiceException {
// note: we do NOT want to get a cahed entry
return ((LdapProvisioning) mProv).getDynamicGroupByQuery(
filterFactory.dynamicGroupById(id),
toZLdapContext(), false);
}
@Override
public void modifyLdapAttrs(Entry entry,
Map<String, ? extends Object> attrs)
throws ServiceException {
((LdapProvisioning) mProv).modifyLdapAttrs(entry, toZLdapContext(), attrs);
}
};
Domain oldDomain = getDomainById(zimbraId, zlc);
if (oldDomain == null)
throw AccountServiceException.NO_SUCH_DOMAIN(zimbraId);
RenameDomain rd = new RenameDomain(this, helper, oldDomain, newDomainName);
rd.execute();
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteCos(String zimbraId) throws ServiceException {
LdapCos c = (LdapCos) get(Key.CosBy.id, zimbraId);
if (c == null)
throw AccountServiceException.NO_SUCH_COS(zimbraId);
if (c.isDefaultCos())
throw ServiceException.INVALID_REQUEST("unable to delete default cos", null);
// TODO: should we go through all accounts with this cos and remove the zimbraCOSId attr?
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_COS);
zlc.deleteEntry(c.getDN());
cosCache.remove(c);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge cos: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public ShareLocator get(Key.ShareLocatorBy keyType, String key) throws ServiceException {
switch(keyType) {
case id:
return getShareLocatorById(key, null, false);
default:
return null;
}
}
@Override
public ShareLocator createShareLocator(String id, Map<String, Object> attrs) throws ServiceException {
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(attrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_SHARELOCATOR);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(attrs);
Set<String> ocs = LdapObjectClass.getShareLocatorObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
entry.setAttr(A_cn, id);
String dn = mDIT.shareLocatorIdToDN(id);
entry.setDN(dn);
zlc.createEntry(entry);
ShareLocator shloc = getShareLocatorById(id, zlc, true);
AttributeManager.getInstance().postModify(attrs, shloc, callbackContext);
return shloc;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.SHARE_LOCATOR_EXISTS(id);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create share locator: " + id, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteShareLocator(String id) throws ServiceException {
LdapShareLocator shloc = (LdapShareLocator) get(Key.ShareLocatorBy.id, id);
if (shloc == null)
throw AccountServiceException.NO_SUCH_SHARE_LOCATOR(id);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_SHARELOCATOR);
zlc.deleteEntry(shloc.getDN());
shareLocatorCache.remove(shloc);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to delete share locator: "+id, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public Server createServer(String name, Map<String, Object> serverAttrs)
throws ServiceException {
name = name.toLowerCase().trim();
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(serverAttrs, null, callbackContext, true);
String authHost = (String)serverAttrs.get(A_zimbraMtaAuthHost);
if (authHost != null) {
serverAttrs.put(A_zimbraMtaAuthURL, URLUtil.getMtaAuthURL(authHost));
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_SERVER);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(serverAttrs);
Set<String> ocs = LdapObjectClass.getServerObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_cn, name);
String dn = mDIT.serverNameToDN(name);
if (!entry.hasAttribute(Provisioning.A_zimbraServiceHostname)) {
entry.setAttr(Provisioning.A_zimbraServiceHostname, name);
}
entry.setDN(dn);
zlc.createEntry(entry);
Server server = getServerById(zimbraIdStr, zlc, true);
AttributeManager.getInstance().postModify(serverAttrs, server, callbackContext);
return server;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.SERVER_EXISTS(name);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create server: " + name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
private Server getServerByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.serverBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapServer(sr.getDN(), sr.getAttributes(), getConfig().getServerDefaults(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getServerByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup server via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private Server getServerById(String zimbraId, ZLdapContext zlc, boolean nocache)
throws ServiceException {
if (zimbraId == null)
return null;
Server s = null;
if (!nocache)
s = serverCache.getById(zimbraId);
if (s == null) {
s = getServerByQuery(filterFactory.serverById(zimbraId), zlc);
serverCache.put(s);
}
return s;
}
private ShareLocator getShareLocatorByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.shareLocatorBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapShareLocator(sr.getDN(), sr.getAttributes(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getShareLocatorByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup share locator via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private ShareLocator getShareLocatorById(String id, ZLdapContext zlc, boolean nocache)
throws ServiceException {
if (id == null)
return null;
ShareLocator shloc = null;
if (!nocache)
shloc = shareLocatorCache.getById(id);
if (shloc == null) {
shloc = getShareLocatorByQuery(filterFactory.shareLocatorById(id), zlc);
shareLocatorCache.put(shloc);
}
return shloc;
}
@Override
public Server get(Key.ServerBy keyType, String key) throws ServiceException {
switch(keyType) {
case name:
return getServerByNameInternal(key);
case id:
return getServerByIdInternal(key);
case serviceHostname:
List<Server> servers = getAllServers();
for (Server server : servers) {
// when replication is enabled, should return server representing current master
if (key.equalsIgnoreCase(server.getAttr(Provisioning.A_zimbraServiceHostname, ""))) {
return server;
}
}
return null;
default:
return null;
}
}
private Server getServerByIdInternal(String zimbraId) throws ServiceException {
return getServerById(zimbraId, null, false);
}
private Server getServerByNameInternal(String name) throws ServiceException {
return getServerByName(name, false);
}
private Server getServerByName(String name, boolean nocache) throws ServiceException {
if (!nocache) {
Server s = serverCache.getByName(name);
if (s != null)
return s;
}
try {
String dn = mDIT.serverNameToDN(name);
ZAttributes attrs = helper.getAttributes(LdapUsage.GET_SERVER, dn);
LdapServer s = new LdapServer(dn, attrs, getConfig().getServerDefaults(), this);
serverCache.put(s);
return s;
} catch (LdapEntryNotFoundException e) {
return null;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup server by name: "+name+" message: "+e.getMessage(), e);
}
}
@Override
public List<Server> getAllServers() throws ServiceException {
return getAllServers(null);
}
@Override
public List<Server> getAllServers(String service) throws ServiceException {
List<Server> result = new ArrayList<Server>();
ZLdapFilter filter;
if (service != null) {
filter = filterFactory.serverByService(service);
} else {
filter = filterFactory.allServers();
}
try {
Map<String, Object> serverDefaults = getConfig().getServerDefaults();
ZSearchResultEnumeration ne = helper.searchDir(mDIT.serverBaseDN(),
filter, ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
LdapServer s = new LdapServer(sr.getDN(), sr.getAttributes(),
serverDefaults, this);
result.add(s);
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all servers", e);
}
if (result.size() > 0)
serverCache.put(result, true);
Collections.sort(result);
return result;
}
private List<Cos> searchCOS(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
List<Cos> result = new ArrayList<Cos>();
try {
ZSearchResultEnumeration ne = helper.searchDir(mDIT.cosBaseDN(), filter,
ZSearchControls.SEARCH_CTLS_SUBTREE(), initZlc, LdapServerType.REPLICA);
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapCos(sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup cos via query: "+
filter.toFilterString() + " message: " + e.getMessage(), e);
}
return result;
}
private void removeServerFromAllCOSes(String serverId, String serverName, ZLdapContext initZlc) {
List<Cos> coses = null;
try {
coses = searchCOS(filterFactory.cosesByMailHostPool(serverId), initZlc);
for (Cos cos: coses) {
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("-"+Provisioning.A_zimbraMailHostPool, serverId);
ZimbraLog.account.info("Removing " + Provisioning.A_zimbraMailHostPool + " " +
serverId + "(" + serverName + ") from cos " + cos.getName());
modifyAttrs(cos, attrs);
// invalidate cached cos
cosCache.remove((LdapCos)cos);
}
} catch (ServiceException se) {
ZimbraLog.account.warn("unable to remove "+serverId+" from all COSes ", se);
return;
}
}
private static class CountingVisitor extends SearchLdapVisitor {
long numAccts = 0;
CountingVisitor() {
super(false);
}
@Override
public void visit(String dn, IAttributes ldapAttrs) {
numAccts++;
}
long getNumAccts() {
return numAccts;
}
};
private long getNumAccountsOnServer(Server server) throws ServiceException {
ZLdapFilter filter = filterFactory.accountsHomedOnServer(server.getServiceHostname());
String base = mDIT.mailBranchBaseDN();
String attrs[] = new String[] {Provisioning.A_zimbraId};
CountingVisitor visitor = new CountingVisitor();
searchLdapOnMaster(base, filter, attrs, visitor);
return visitor.getNumAccts();
}
@Override
public void deleteServer(String zimbraId) throws ServiceException {
LdapServer server = (LdapServer) getServerByIdInternal(zimbraId);
if (server == null)
throw AccountServiceException.NO_SUCH_SERVER(zimbraId);
// check that no account is still on this server
long numAcctsOnServer = getNumAccountsOnServer(server);
if (numAcctsOnServer != 0) {
throw ServiceException.INVALID_REQUEST("There are " + numAcctsOnServer +
" account(s) on this server.", null);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_SERVER);
removeServerFromAllCOSes(zimbraId, server.getName(), zlc);
zlc.deleteEntry(server.getDN());
serverCache.remove(server);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge server: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
/*
* Distribution lists.
*/
@Override
public DistributionList createDistributionList(String listAddress,
Map<String, Object> listAttrs)
throws ServiceException {
return createDistributionList(listAddress, listAttrs, null);
}
private DistributionList createDistributionList(String listAddress,
Map<String, Object> listAttrs, Account creator)
throws ServiceException {
SpecialAttrs specialAttrs = mDIT.handleSpecialAttrs(listAttrs);
String baseDn = specialAttrs.getLdapBaseDn();
listAddress = listAddress.toLowerCase().trim();
String parts[] = listAddress.split("@");
if (parts.length != 2)
throw ServiceException.INVALID_REQUEST("must be valid list address: " + listAddress, null);
String localPart = parts[0];
String domain = parts[1];
domain = IDNUtil.toAsciiDomainName(domain);
listAddress = localPart + "@" + domain;
validEmailAddress(listAddress);
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
callbackContext.setCreatingEntryName(listAddress);
AttributeManager.getInstance().preModify(listAttrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_DISTRIBUTIONLIST);
Domain d = getDomainByAsciiName(domain, zlc);
if (d == null)
throw AccountServiceException.NO_SUCH_DOMAIN(domain);
if (!d.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(listAttrs);
Set<String> ocs = LdapObjectClass.getDistributionListObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_mail, listAddress);
// unlike accounts (which have a zimbraMailDeliveryAddress for the primary,
// and zimbraMailAliases only for aliases), DLs use zibraMailAlias for both.
// Postfix uses these two attributes to route mail, and zimbraMailDeliveryAddress
// indicates that something has a physical mailbox, which DLs don't.
entry.setAttr(A_zimbraMailAlias, listAddress);
// by default a distribution list is always created enabled
if (!entry.hasAttribute(Provisioning.A_zimbraMailStatus)) {
entry.setAttr(A_zimbraMailStatus, MAIL_STATUS_ENABLED);
}
String displayName = entry.getAttrString(Provisioning.A_displayName);
if (displayName != null) {
entry.setAttr(A_cn, displayName);
}
entry.setAttr(A_uid, localPart);
setGroupHomeServer(entry, creator);
String dn = mDIT.distributionListDNCreate(baseDn, entry.getAttributes(), localPart, domain);
entry.setDN(dn);
zlc.createEntry(entry);
DistributionList dlist = getDLBasic(DistributionListBy.id, zimbraIdStr, zlc);
if (dlist != null) {
AttributeManager.getInstance().postModify(listAttrs, dlist, callbackContext);
removeExternalAddrsFromAllDynamicGroups(dlist.getAllAddrsSet(), zlc);
allDLs.addGroup(dlist);
} else {
throw ServiceException.FAILURE("unable to get distribution list after creating LDAP entry: "+
listAddress, null);
}
return dlist;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(listAddress);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create distribution list: "+listAddress, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public List<DistributionList> getDistributionLists(DistributionList list,
boolean directOnly, Map<String, String> via) throws ServiceException {
return getContainingDistributionLists(list, directOnly, via);
}
private DistributionList getDistributionListByQuery(String base, ZLdapFilter filter,
ZLdapContext initZlc, boolean basicAttrsOnly) throws ServiceException {
String[] returnAttrs = basicAttrsOnly ? BASIC_DL_ATTRS : null;
DistributionList dl = null;
try {
ZSearchControls searchControls = ZSearchControls.createSearchControls(
ZSearchScope.SEARCH_SCOPE_SUBTREE, ZSearchControls.SIZE_UNLIMITED, returnAttrs);
ZSearchResultEnumeration ne = helper.searchDir(base, filter,
searchControls, initZlc, LdapServerType.REPLICA);
if (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
dl = makeDistributionList(sr.getDN(), sr.getAttributes(), basicAttrsOnly);
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup distribution list via query: "+
filter.toFilterString() + " message: "+e.getMessage(), e);
}
return dl;
}
@Override
public void renameDistributionList(String zimbraId, String newEmail) throws ServiceException {
newEmail = IDNUtil.toAsciiEmail(newEmail);
validEmailAddress(newEmail);
boolean domainChanged = false;
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_DISTRIBUTIONLIST);
LdapDistributionList dl = (LdapDistributionList) getDistributionListById(zimbraId, zlc);
if (dl == null) {
throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(zimbraId);
}
groupCache.remove(dl);
String oldEmail = dl.getName();
String oldDomain = EmailUtil.getValidDomainPart(oldEmail);
newEmail = newEmail.toLowerCase().trim();
String[] parts = EmailUtil.getLocalPartAndDomain(newEmail);
if (parts == null)
throw ServiceException.INVALID_REQUEST("bad value for newName", null);
String newLocal = parts[0];
String newDomain = parts[1];
domainChanged = !oldDomain.equals(newDomain);
Domain domain = getDomainByAsciiName(newDomain, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(newDomain);
}
if (domainChanged) {
// make sure the new domain is a local domain
if (!domain.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
}
Map<String, Object> attrs = new HashMap<String, Object>();
ReplaceAddressResult replacedMails = replaceMailAddresses(dl, Provisioning.A_mail, oldEmail, newEmail);
if (replacedMails.newAddrs().length == 0) {
// Set mail to newName if the account currently does not have a mail
attrs.put(Provisioning.A_mail, newEmail);
} else {
attrs.put(Provisioning.A_mail, replacedMails.newAddrs());
}
ReplaceAddressResult replacedAliases = replaceMailAddresses(dl, Provisioning.A_zimbraMailAlias, oldEmail, newEmail);
if (replacedAliases.newAddrs().length > 0) {
attrs.put(Provisioning.A_zimbraMailAlias, replacedAliases.newAddrs());
String newDomainDN = mDIT.domainToAccountSearchDN(newDomain);
// check up front if any of renamed aliases already exists in the new domain (if domain also got changed)
if (domainChanged && addressExistsUnderDN(zlc, newDomainDN, replacedAliases.newAddrs())) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(newEmail);
}
}
ReplaceAddressResult replacedAllowAddrForDelegatedSender =
replaceMailAddresses(dl, Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
oldEmail, newEmail);
if (replacedAllowAddrForDelegatedSender.newAddrs().length > 0) {
attrs.put(Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
replacedAllowAddrForDelegatedSender.newAddrs());
}
String oldDn = dl.getDN();
String newDn = mDIT.distributionListDNRename(oldDn, newLocal, domain.getName());
boolean dnChanged = (!oldDn.equals(newDn));
if (dnChanged) {
// uid will be changed during renameEntry, so no need to modify it
// OpenLDAP is OK modifying it, as long as it matches the new DN, but
// InMemoryDirectoryServer does not like it.
attrs.remove(A_uid);
} else {
/*
* always reset uid to the local part, because in non default DIT the naming RDN might not
* be uid, and ctxt.rename won't change the uid to the new localpart in that case.
*/
attrs.put(A_uid, newLocal);
}
// move over the distribution list entry
if (dnChanged) {
zlc.renameEntry(oldDn, newDn);
}
dl = (LdapDistributionList) getDistributionListById(zimbraId, zlc);
// rename the distribution list and all it's renamed aliases to the new name
// in all distribution lists.
// Doesn't throw exceptions, just logs.
renameAddressesInAllDistributionLists(oldEmail, newEmail, replacedAliases);
// MOVE OVER ALL aliases
// doesn't throw exceptions, just logs
if (domainChanged) {
String newUid = dl.getAttr(Provisioning.A_uid);
moveAliases(zlc, replacedAliases, newDomain, newUid, oldDn, newDn, oldDomain, newDomain);
}
// this is non-atomic. i.e., rename could succeed and updating A_mail
// could fail. So catch service exception here and log error
try {
modifyAttrsInternal(dl, zlc, attrs);
} catch (ServiceException e) {
ZimbraLog.account.error("distribution list renamed to " + newLocal +
" but failed to move old name's LDAP attributes", e);
throw e;
}
removeExternalAddrsFromAllDynamicGroups(dl.getAllAddrsSet(), zlc);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(newEmail);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename distribution list: " + zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
if (domainChanged) {
PermissionCache.invalidateCache();
}
}
@Override
public DistributionList get(Key.DistributionListBy keyType, String key)
throws ServiceException {
switch(keyType) {
case id:
return getDistributionListByIdInternal(key);
case name:
DistributionList dl = getDistributionListByNameInternal(key);
if (dl == null) {
String localDomainAddr = getEmailAddrByDomainAlias(key);
if (localDomainAddr != null) {
dl = getDistributionListByNameInternal(localDomainAddr);
}
}
return dl;
default:
return null;
}
}
private DistributionList getDistributionListById(String zimbraId, ZLdapContext zlc)
throws ServiceException {
return getDistributionListByQuery(mDIT.mailBranchBaseDN(),
filterFactory.distributionListById(zimbraId),
zlc, false);
}
private DistributionList getDistributionListByIdInternal(String zimbraId)
throws ServiceException {
return getDistributionListById(zimbraId, null);
}
@Override
public void deleteDistributionList(String zimbraId) throws ServiceException {
LdapDistributionList dl = (LdapDistributionList) getDistributionListByIdInternal(zimbraId);
if (dl == null) {
throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(zimbraId);
}
deleteDistributionList(dl);
}
private void deleteDistributionList(LdapDistributionList dl) throws ServiceException {
String zimbraId = dl.getId();
// make a copy of all addrs of this DL, after the delete all aliases on this dl
// object will be gone, but we need to remove them from the allgroups cache after the DL is deleted
Set<String> addrs = new HashSet<String>(dl.getMultiAttrSet(Provisioning.A_mail));
// remove the DL from all DLs
removeAddressFromAllDistributionLists(dl.getName()); // this doesn't throw any exceptions
// delete all aliases of the DL
String aliases[] = dl.getAliases();
if (aliases != null) {
String dlName = dl.getName();
for (int i=0; i < aliases.length; i++) {
// the primary name shows up in zimbraMailAlias on the entry, don't bother to remove
// this "alias" if it is the primary name, the entire entry will be deleted anyway.
if (!dlName.equalsIgnoreCase(aliases[i])) {
removeAlias(dl, aliases[i]); // this also removes each alias from any DLs
}
}
}
// delete all grants granted to the DL
try {
RightCommand.revokeAllRights(this, GranteeType.GT_GROUP, zimbraId);
} catch (ServiceException e) {
// eat the exception and continue
ZimbraLog.account.warn("cannot revoke grants", e);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_DISTRIBUTIONLIST);
zlc.deleteEntry(dl.getDN());
groupCache.remove(dl);
allDLs.removeGroup(addrs);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge distribution list: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
PermissionCache.invalidateCache();
}
private DistributionList getDistributionListByNameInternal(String listAddress)
throws ServiceException {
listAddress = IDNUtil.toAsciiEmail(listAddress);
return getDistributionListByQuery(mDIT.mailBranchBaseDN(),
filterFactory.distributionListByName(listAddress), null, false);
}
@Override
public boolean isDistributionList(String addr) {
boolean isDL = allDLs.isGroup(addr);
if (!isDL) {
try {
addr = getEmailAddrByDomainAlias(addr);
if (addr != null) {
isDL = allDLs.isGroup(addr);
}
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get local domain address of " + addr, e);
}
}
return isDL;
}
private Group getGroupFromCache(Key.DistributionListBy keyType, String key) {
switch(keyType) {
case id:
return groupCache.getById(key);
case name:
return groupCache.getByName(key);
default:
return null;
}
}
private void putInGroupCache(Group group) {
groupCache.put(group);
}
private DistributionList getDLFromCache(Key.DistributionListBy keyType, String key) {
Group group = getGroupFromCache(keyType, key);
if (group instanceof DistributionList) {
return (DistributionList) group;
} else {
return null;
}
}
void removeGroupFromCache(Key.DistributionListBy keyType, String key) {
Group group = getGroupFromCache(keyType, key);
if (group != null) {
removeFromCache(group);
}
}
private GroupMembership computeUpwardMembership(Entry entry) throws ServiceException {
Map<String, String> via = new HashMap<String, String>();
List<DistributionList> lists = getContainingDistributionLists(entry, false, via);
return computeUpwardMembership(lists);
}
private GroupMembership computeUpwardMembership(List<DistributionList> lists) {
List<MemberOf> groups = new ArrayList<MemberOf>();
List<String> groupIds = new ArrayList<String>();
for (DistributionList dl : lists) {
groups.add(new MemberOf(dl.getId(), dl.isIsAdminGroup(), false));
groupIds.add(dl.getId());
}
return new GroupMembership(groups, groupIds);
}
// filter out non-admin groups from an AclGroups instance
private GroupMembership getAdminAclGroups(GroupMembership aclGroups) {
List<MemberOf> groups = new ArrayList<MemberOf>();
List<String> groupIds = new ArrayList<String>();
List<MemberOf> memberOf = aclGroups.memberOf();
for (MemberOf mo : memberOf) {
if (mo.isAdminGroup()) {
groups.add(mo);
groupIds.add(mo.getId());
}
}
groups = Collections.unmodifiableList(groups);
groupIds = Collections.unmodifiableList(groupIds);
return new GroupMembership(groups, groupIds);
}
@Override
public GroupMembership getGroupMembership(Account acct, boolean adminGroupsOnly)
throws ServiceException {
EntryCacheDataKey cacheKey = adminGroupsOnly ?
EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP_ADMINS_ONLY :
EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP;
GroupMembership groups = (GroupMembership)acct.getCachedData(cacheKey);
if (groups != null) {
return groups;
}
//
// static groups
//
groups = computeUpwardMembership(acct);
//
// append dynamic groups
//
List<DynamicGroup> dynGroups = getContainingDynamicGroups(acct);
for (DynamicGroup dynGroup : dynGroups) {
groups.append(new MemberOf(dynGroup.getId(), dynGroup.isIsAdminGroup(), true),
dynGroup.getId());
}
// cache it
acct.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP, groups);
// filter out non-admin groups
if (adminGroupsOnly) {
groups = getAdminAclGroups(groups);
acct.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP_ADMINS_ONLY, groups);
}
return groups;
}
@Override
public GroupMembership getGroupMembership(DistributionList dl, boolean adminGroupsOnly)
throws ServiceException {
EntryCacheDataKey cacheKey = adminGroupsOnly ?
EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP_ADMINS_ONLY :
EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP;
GroupMembership groups = (GroupMembership)dl.getCachedData(cacheKey);
if (groups != null) {
return groups;
}
groups = computeUpwardMembership(dl);
dl.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP, groups);
if (adminGroupsOnly) {
groups = getAdminAclGroups(groups); // filter out non-admin groups
dl.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP_ADMINS_ONLY, groups);
}
return groups;
}
@Override
public Server getLocalServer() throws ServiceException {
String hostname = LC.zimbra_server_hostname.value();
if (hostname == null) {
Zimbra.halt("zimbra_server_hostname not specified in localconfig.xml");
}
Server local = getServerByNameInternal(hostname);
if (local == null) {
Zimbra.halt("Could not find an LDAP entry for server '" + hostname + "'");
}
return local;
}
public static final long TIMESTAMP_WINDOW = Constants.MILLIS_PER_MINUTE * 5;
private void checkAccountStatus(Account acct, Map<String, Object> authCtxt)
throws ServiceException {
/*
* We no longer do this reload(see bug 18981):
* Stale data can be read back if there are replication delays and the account is
* refreshed from a not-caught-up replica.
*
* We put this reload back for bug 46767.
* SetPassword is always proxied to the home server,
* but not the AuthRequest. Not reloading here creates the problem that after a
* SetPassword, if an AuthRequest (or auth from other protocols: imap/pop3) comes
* in on a non-home server, the new password won't get hornored; even worse, the old
* password will! This hole will last until the account is aged out of cache.
*
* We have to put back this reload.
* - if we relaod from the master, bug 18981 and bug 46767 will be taken care of,
* but will regress bug 20634 - master down should not block login.
*
* - if we reload from the replica,
* 1. if the replica is always caught up, everything is fine.
*
* 2. if the replica is slow, bug 18981 and bug 46767 can still happen.
* To minimize impact to bug 18981, we do this reload only when the server
* is not the home server of the account.
* For bug 46767, customer will have to fix their replica, period!
*
* Note, if nginx is fronting, auth is always redirected to the home
* server, so bug 46767 should not happen and the reload should never
* be triggered(good for bug 18981).
*/
if (!onLocalServer(acct)) {
reload(acct, false); // reload from the replica
}
String accountStatus = acct.getAccountStatus(Provisioning.getInstance());
if (accountStatus == null) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "missing account status");
}
if (accountStatus.equals(Provisioning.ACCOUNT_STATUS_MAINTENANCE)) {
throw AccountServiceException.MAINTENANCE_MODE();
}
if (!(accountStatus.equals(Provisioning.ACCOUNT_STATUS_ACTIVE) ||
accountStatus.equals(Provisioning.ACCOUNT_STATUS_LOCKOUT))) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "account(or domain) status is " +
accountStatus);
}
}
@Override
public void preAuthAccount(Account acct, String acctValue, String acctBy,
long timestamp, long expires, String preAuth, Map<String, Object> authCtxt)
throws ServiceException {
preAuthAccount(acct, acctValue, acctBy, timestamp, expires, preAuth, false, authCtxt);
}
@Override
public void preAuthAccount(Account acct, String acctValue, String acctBy,
long timestamp, long expires, String preAuth, boolean admin,
Map<String, Object> authCtxt)
throws ServiceException {
try {
preAuth(acct, acctValue, acctBy, timestamp, expires, preAuth, admin, authCtxt);
ZimbraLog.security.info(ZimbraLog.encodeAttrs(
new String[] {"cmd", "PreAuth","account", acct.getName(), "admin", admin+""}));
} catch (AuthFailedServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "PreAuth","account", acct.getName(), "admin", admin+"", "error", e.getMessage()+e.getReason(", %s")}));
throw e;
} catch (ServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "PreAuth","account", acct.getName(), "admin", admin+"", "error", e.getMessage()}));
throw e;
}
}
@Override
public void preAuthAccount(Domain domain, String acctValue, String acctBy,
long timestamp, long expires, String preAuth, Map<String, Object> authCtxt)
throws ServiceException {
verifyPreAuth(domain, null, acctValue, acctBy, timestamp, expires, preAuth, false, authCtxt);
ZimbraLog.security.info(ZimbraLog.encodeAttrs(
new String[] {"cmd", "PreAuth","account", acctValue}));
}
private void verifyPreAuth(Account acct, String acctValue, String acctBy, long timestamp, long expires,
String preAuth, boolean admin, Map<String, Object> authCtxt) throws ServiceException {
checkAccountStatus(acct, authCtxt);
verifyPreAuth(Provisioning.getInstance().getDomain(acct), acct.getName(),
acctValue, acctBy, timestamp, expires, preAuth, admin,authCtxt);
}
void verifyPreAuth(Domain domain, String acctNameForLogging,
String acctValue, String acctBy, long timestamp, long expires,
String preAuth, boolean admin, Map<String, Object> authCtxt)
throws ServiceException {
if (preAuth == null || preAuth.length() == 0)
throw ServiceException.INVALID_REQUEST("preAuth must not be empty", null);
if (acctNameForLogging == null) {
acctNameForLogging = acctValue;
}
// see if domain is configured for preauth
String domainPreAuthKey = domain.getAttr(Provisioning.A_zimbraPreAuthKey, null);
if (domainPreAuthKey == null)
throw ServiceException.INVALID_REQUEST("domain is not configured for preauth", null);
// see if request is recent
long now = System.currentTimeMillis();
long diff = Math.abs(now-timestamp);
if (diff > TIMESTAMP_WINDOW) {
Date nowDate = new Date(now);
Date preauthDate = new Date(timestamp);
throw AuthFailedServiceException.AUTH_FAILED(acctNameForLogging,
AuthMechanism.namePassedIn(authCtxt),
"preauth timestamp is too old, server time: " + nowDate.toString() +
", preauth timestamp: " + preauthDate.toString());
}
// compute expected preAuth
HashMap<String,String> params = new HashMap<String,String>();
params.put("account", acctValue);
if (admin) params.put("admin", "1");
params.put("by", acctBy);
params.put("timestamp", timestamp+"");
params.put("expires", expires+"");
String computedPreAuth = PreAuthKey.computePreAuth(params, domainPreAuthKey);
if (!computedPreAuth.equalsIgnoreCase(preAuth)) {
throw AuthFailedServiceException.AUTH_FAILED(acctNameForLogging,
AuthMechanism.namePassedIn(authCtxt), "preauth mismatch");
}
}
private void preAuth(Account acct, String acctValue, String acctBy, long timestamp, long expires,
String preAuth, boolean admin, Map<String, Object> authCtxt) throws ServiceException {
LdapLockoutPolicy lockoutPolicy = new LdapLockoutPolicy(this, acct);
try {
if (lockoutPolicy.isLockedOut()) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "account lockout");
}
// attempt to verify the preauth
verifyPreAuth(acct, acctValue, acctBy, timestamp, expires, preAuth, admin, authCtxt);
lockoutPolicy.successfulLogin();
} catch (AccountServiceException e) {
lockoutPolicy.failedLogin();
// re-throw original exception
throw e;
}
// update/check last logon
updateLastLogon(acct);
}
@Override
public void authAccount(Account acct, String password, AuthContext.Protocol proto)
throws ServiceException {
authAccount(acct, password, proto, null);
}
@Override
public void authAccount(Account acct, String password, AuthContext.Protocol proto,
Map<String, Object> authCtxt)
throws ServiceException {
try {
if (password == null || password.equals("")) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "empty password");
}
if (authCtxt == null)
authCtxt = new HashMap<String, Object>();
// add proto to the auth context
authCtxt.put(AuthContext.AC_PROTOCOL, proto);
authAccount(acct, password, true, authCtxt);
ZimbraLog.security.info(ZimbraLog.encodeAttrs(
new String[] {"cmd", "Auth","account", acct.getName(), "protocol", proto.toString()}));
} catch (AuthFailedServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "Auth","account", acct.getName(), "protocol", proto.toString(), "error", e.getMessage() + e.getReason(", %s")}));
throw e;
} catch (ServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "Auth","account", acct.getName(), "protocol", proto.toString(), "error", e.getMessage()}));
throw e;
}
}
private void authAccount(Account acct, String password,
boolean checkPasswordPolicy, Map<String, Object> authCtxt)
throws ServiceException {
checkAccountStatus(acct, authCtxt);
AuthMechanism authMech = AuthMechanism.newInstance(acct, authCtxt);
verifyPassword(acct, password, authMech, authCtxt);
// true: authenticating
// false: changing password (we do *not* want to update last login in this case)
if (!checkPasswordPolicy)
return;
if (authMech.checkPasswordAging()) {
// below this point, the only fault that may be thrown is CHANGE_PASSWORD
int maxAge = acct.getIntAttr(Provisioning.A_zimbraPasswordMaxAge, 0);
if (maxAge > 0) {
Date lastChange = acct.getGeneralizedTimeAttr(Provisioning.A_zimbraPasswordModifiedTime, null);
if (lastChange != null) {
long last = lastChange.getTime();
long curr = System.currentTimeMillis();
if ((last+(Constants.MILLIS_PER_DAY * maxAge)) < curr)
throw AccountServiceException.CHANGE_PASSWORD();
}
}
boolean mustChange = acct.getBooleanAttr(Provisioning.A_zimbraPasswordMustChange, false);
if (mustChange)
throw AccountServiceException.CHANGE_PASSWORD();
}
// update/check last logon
updateLastLogon(acct);
}
@Override
public void accountAuthed(Account acct) throws ServiceException {
updateLastLogon(acct);
}
@Override
public void ssoAuthAccount(Account acct, AuthContext.Protocol proto,
Map<String, Object> authCtxt)
throws ServiceException {
try {
ssoAuth(acct, authCtxt);
ZimbraLog.security.info(ZimbraLog.encodeAttrs(
new String[] {"cmd", "SSOAuth","account", acct.getName(), "protocol", proto.toString()}));
} catch (AuthFailedServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "SSOAuth","account", acct.getName(), "protocol", proto.toString(), "error", e.getMessage() + e.getReason(", %s")}));
throw e;
} catch (ServiceException e) {
ZimbraLog.security.warn(ZimbraLog.encodeAttrs(
new String[] {"cmd", "SSOAuth","account", acct.getName(), "protocol", proto.toString(), "error", e.getMessage()}));
throw e;
}
}
private void ssoAuth(Account acct, Map<String, Object> authCtxt) throws ServiceException {
checkAccountStatus(acct, authCtxt);
LdapLockoutPolicy lockoutPolicy = new LdapLockoutPolicy(this, acct);
try {
if (lockoutPolicy.isLockedOut()) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "account lockout");
}
// yes, SSO can unlock the acount
lockoutPolicy.successfulLogin();
} catch (AccountServiceException e) {
lockoutPolicy.failedLogin();
throw e;
}
updateLastLogon(acct);
}
private void updateLastLogon(Account acct) throws ServiceException {
Config config = Provisioning.getInstance().getConfig();
long freq = config.getTimeInterval(
Provisioning.A_zimbraLastLogonTimestampFrequency,
com.zimbra.cs.util.Config.D_ZIMBRA_LAST_LOGON_TIMESTAMP_FREQUENCY);
// never update timestamp if frequency is 0
if (freq == 0)
return;
Date lastLogon = acct.getGeneralizedTimeAttr(Provisioning.A_zimbraLastLogonTimestamp, null);
if (lastLogon == null) {
Map<String, String> attrs = new HashMap<String, String>();
attrs.put(Provisioning.A_zimbraLastLogonTimestamp, DateUtil.toGeneralizedTime(new Date()));
try {
modifyAttrs(acct, attrs);
} catch (ServiceException e) {
ZimbraLog.account.warn("updating zimbraLastLogonTimestamp", e);
}
} else {
long current = System.currentTimeMillis();
if (current - freq >= lastLogon.getTime()) {
Map<String, String> attrs = new HashMap<String , String>();
attrs.put(Provisioning.A_zimbraLastLogonTimestamp, DateUtil.toGeneralizedTime(new Date()));
try {
modifyAttrs(acct, attrs);
} catch (ServiceException e) {
ZimbraLog.account.warn("updating zimbraLastLogonTimestamp", e);
}
}
}
}
private static Provisioning.Result toResult(ServiceException e, String dn) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
return Check.toResult((IOException) cause, dn);
} else if (e instanceof LdapException) {
LdapException ldapException = (LdapException) e;
Throwable detail = ldapException.getDetail();
if (detail instanceof IOException) {
return Check.toResult((IOException) detail, dn);
} else if (ldapException instanceof LdapEntryNotFoundException ||
detail instanceof LdapEntryNotFoundException) {
return new Provisioning.Result(Check.STATUS_NAME_NOT_FOUND, e, dn);
} else if (ldapException instanceof LdapInvalidSearchFilterException ||
detail instanceof LdapInvalidSearchFilterException) {
return new Provisioning.Result(Check.STATUS_INVALID_SEARCH_FILTER, e, dn);
}
}
// return a generic error for all other causes
return new Provisioning.Result(Check.STATUS_AUTH_FAILED, e, dn);
}
private void ldapAuthenticate(String urls[], boolean requireStartTLS, String principal, String password)
throws ServiceException {
if (password == null || password.equals("")) {
throw AccountServiceException.AuthFailedServiceException.AUTH_FAILED("empty password");
}
LdapClient.externalLdapAuthenticate(urls, requireStartTLS, principal, password, "external LDAP auth");
}
/*
* search for the auth DN for the user, authneticate to the result DN
*/
private void ldapAuthenticate(String url[], boolean wantStartTLS, String password,
String searchBase, String searchFilter, String searchDn, String searchPassword)
throws ServiceException {
if (password == null || password.equals("")) {
throw AccountServiceException.AuthFailedServiceException.AUTH_FAILED("empty password");
}
ExternalLdapConfig config = new ExternalLdapConfig(url, wantStartTLS,
null, searchDn, searchPassword, null, "external LDAP auth");
String resultDn = null;
String tooMany = null;
ZLdapContext zlc = null;
try {
zlc = LdapClient.getExternalContext(config, LdapUsage.LDAP_AUTH_EXTERNAL);
ZSearchResultEnumeration ne = zlc.searchDir(searchBase,
filterFactory.fromFilterString(FilterId.LDAP_AUTHENTICATE, searchFilter),
ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
if (resultDn == null) {
resultDn = sr.getDN();
} else {
tooMany = sr.getDN();
break;
}
}
ne.close();
} finally {
LdapClient.closeContext(zlc);
}
if (tooMany != null) {
ZimbraLog.account.warn(String.format(
"ldapAuthenticate searchFilter returned more then one result: (dn1=%s, dn2=%s, filter=%s)",
resultDn, tooMany, searchFilter));
throw AccountServiceException.AuthFailedServiceException.AUTH_FAILED("too many results from search filter!");
} else if (resultDn == null) {
throw AccountServiceException.AuthFailedServiceException.AUTH_FAILED("empty search");
}
if (ZimbraLog.account.isDebugEnabled()) ZimbraLog.account.debug("search filter matched: "+resultDn);
ldapAuthenticate(url, wantStartTLS, resultDn, password);
}
@Override
public Provisioning.Result checkAuthConfig(Map attrs, String name, String password)
throws ServiceException {
AuthMech mech = AuthMech.fromString(Check.getRequiredAttr(attrs, Provisioning.A_zimbraAuthMech));
if (!(mech == AuthMech.ldap || mech == AuthMech.ad)) {
throw ServiceException.INVALID_REQUEST("auth mech must be: "+
AuthMech.ldap.name() + " or " + AuthMech.ad.name(), null);
}
String url[] = Check.getRequiredMultiAttr(attrs, Provisioning.A_zimbraAuthLdapURL);
// TODO, need admin UI work for zimbraAuthLdapStartTlsEnabled
String startTLSEnabled = (String) attrs.get(Provisioning.A_zimbraAuthLdapStartTlsEnabled);
boolean requireStartTLS = startTLSEnabled == null ? false : ProvisioningConstants.TRUE.equals(startTLSEnabled);
try {
String searchFilter = (String) attrs.get(Provisioning.A_zimbraAuthLdapSearchFilter);
if (searchFilter != null) {
String searchPassword = (String) attrs.get(Provisioning.A_zimbraAuthLdapSearchBindPassword);
String searchDn = (String) attrs.get(Provisioning.A_zimbraAuthLdapSearchBindDn);
String searchBase = (String) attrs.get(Provisioning.A_zimbraAuthLdapSearchBase);
if (searchBase == null) searchBase = "";
searchFilter = LdapUtil.computeDn(name, searchFilter);
if (ZimbraLog.account.isDebugEnabled()) ZimbraLog.account.debug("auth with search filter of "+searchFilter);
ldapAuthenticate(url, requireStartTLS, password, searchBase, searchFilter, searchDn, searchPassword);
return new Provisioning.Result(Check.STATUS_OK, "", searchFilter);
}
String bindDn = (String) attrs.get(Provisioning.A_zimbraAuthLdapBindDn);
if (bindDn != null) {
String dn = LdapUtil.computeDn(name, bindDn);
if (ZimbraLog.account.isDebugEnabled()) ZimbraLog.account.debug("auth with bind dn template of "+dn);
ldapAuthenticate(url, requireStartTLS, dn, password);
return new Provisioning.Result(Check.STATUS_OK, "", dn);
}
throw ServiceException.INVALID_REQUEST("must specify "+Provisioning.A_zimbraAuthLdapSearchFilter + " or " +
Provisioning.A_zimbraAuthLdapBindDn, null);
} catch (ServiceException e) {
return toResult(e, "");
}
}
@Override
public Provisioning.Result checkGalConfig(Map attrs, String query, int limit, GalOp galOp)
throws ServiceException {
GalMode mode = GalMode.fromString(Check.getRequiredAttr(attrs, Provisioning.A_zimbraGalMode));
if (mode != GalMode.ldap)
throw ServiceException.INVALID_REQUEST("gal mode must be: "+GalMode.ldap.toString(), null);
GalParams.ExternalGalParams galParams = new GalParams.ExternalGalParams(attrs, galOp);
LdapGalMapRules rules = new LdapGalMapRules(Provisioning.getInstance().getConfig(), false);
try {
SearchGalResult result = null;
if (galOp == GalOp.autocomplete)
result = LdapGalSearch.searchLdapGal(galParams, GalOp.autocomplete, query, limit, rules, null, null);
else if (galOp == GalOp.search)
result = LdapGalSearch.searchLdapGal(galParams, GalOp.search, query, limit, rules, null, null);
else if (galOp == GalOp.sync)
result = LdapGalSearch.searchLdapGal(galParams, GalOp.sync, query, limit, rules, "", null);
else
throw ServiceException.INVALID_REQUEST("invalid GAL op: "+galOp.toString(), null);
return new Provisioning.GalResult(Check.STATUS_OK, "", result.getMatches());
} catch (ServiceException e) {
return toResult(e, "");
}
}
@Override
public void externalLdapAuth(Domain domain, AuthMech authMech,
Account acct, String password, Map<String, Object> authCtxt)
throws ServiceException {
externalLdapAuth(domain, authMech, acct, null, password, authCtxt);
}
@Override
public void externalLdapAuth(Domain d, AuthMech authMech,
String principal, String password, Map<String, Object> authCtxt)
throws ServiceException {
externalLdapAuth(d, authMech, null, principal, password, authCtxt);
}
void externalLdapAuth(Domain d, AuthMech authMech, Account acct, String principal,
String password, Map<String, Object> authCtxt) throws ServiceException {
// exactly one of acct or principal is not null
// when acct is null, we are from the auto provisioning path
assert((acct == null) != (principal == null));
String url[] = d.getMultiAttr(Provisioning.A_zimbraAuthLdapURL);
if (url == null || url.length == 0) {
String msg = "attr not set "+Provisioning.A_zimbraAuthLdapURL;
ZimbraLog.account.fatal(msg);
throw ServiceException.FAILURE(msg, null);
}
boolean requireStartTLS = d.getBooleanAttr(Provisioning.A_zimbraAuthLdapStartTlsEnabled, false);
try {
// try explicit externalDn first
if (acct != null) {
String externalDn = acct.getAttr(Provisioning.A_zimbraAuthLdapExternalDn);
if (externalDn != null) {
ZimbraLog.account.debug("auth with explicit dn of "+externalDn);
ldapAuthenticate(url, requireStartTLS, externalDn, password);
return;
}
// principal must be null, user account's name for principal
principal = acct.getName();
}
// principal must not be null by now
String searchFilter = d.getAttr(Provisioning.A_zimbraAuthLdapSearchFilter);
if (searchFilter != null && AuthMech.ad != authMech) {
String searchPassword = d.getAttr(Provisioning.A_zimbraAuthLdapSearchBindPassword);
String searchDn = d.getAttr(Provisioning.A_zimbraAuthLdapSearchBindDn);
String searchBase = d.getAttr(Provisioning.A_zimbraAuthLdapSearchBase);
if (searchBase == null) {
searchBase = "";
}
searchFilter = LdapUtil.computeDn(principal, searchFilter);
ZimbraLog.account.debug("auth with search filter of "+searchFilter);
ldapAuthenticate(url, requireStartTLS, password, searchBase, searchFilter, searchDn, searchPassword);
return;
}
String bindDn = d.getAttr(Provisioning.A_zimbraAuthLdapBindDn);
if (bindDn != null) {
String dn = LdapUtil.computeDn(principal, bindDn);
ZimbraLog.account.debug("auth with bind dn template of "+dn);
ldapAuthenticate(url, requireStartTLS, dn, password);
return;
}
} catch (ServiceException e) {
throw AuthFailedServiceException.AUTH_FAILED(principal,
AuthMechanism.namePassedIn(authCtxt), "external LDAP auth failed, "+e.getMessage(), e);
}
String msg = "one of the following attrs must be set "+
Provisioning.A_zimbraAuthLdapBindDn+", "+Provisioning.A_zimbraAuthLdapSearchFilter;
ZimbraLog.account.fatal(msg);
throw ServiceException.FAILURE(msg, null);
}
@Override
public void zimbraLdapAuthenticate(Account acct, String password,
Map<String, Object> authCtxt) throws ServiceException {
try {
LdapClient.zimbraLdapAuthenticate(((LdapEntry)acct).getDN(), password);
} catch (ServiceException e) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), e.getMessage(), e);
}
}
private void verifyPassword(Account acct, String password, AuthMechanism authMech,
Map<String, Object> authCtxt)
throws ServiceException {
LdapLockoutPolicy lockoutPolicy = new LdapLockoutPolicy(this, acct);
try {
if (lockoutPolicy.isLockedOut()) {
throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
AuthMechanism.namePassedIn(authCtxt), "account lockout");
}
// attempt to verify the password
verifyPasswordInternal(acct, password, authMech, authCtxt);
lockoutPolicy.successfulLogin();
} catch (AccountServiceException e) {
// TODO: only consider it failed if exception was due to password-mismatch
lockoutPolicy.failedLogin();
// re-throw original exception
throw e;
}
}
/*
* authAccount does all the status/mustChange checks, this just takes the
* password and auths the user
*/
private void verifyPasswordInternal(Account acct, String password,
AuthMechanism authMech, Map<String, Object> context)
throws ServiceException {
Domain domain = Provisioning.getInstance().getDomain(acct);
boolean allowFallback = true;
if (!authMech.isZimbraAuth()) {
allowFallback =
domain.getBooleanAttr(Provisioning.A_zimbraAuthFallbackToLocal, false) ||
acct.getBooleanAttr(Provisioning.A_zimbraIsAdminAccount, false) ||
acct.getBooleanAttr(Provisioning.A_zimbraIsDomainAdminAccount, false);
}
try {
authMech.doAuth(this, domain, acct, password, context);
AuthMech authedByMech = authMech.getMechanism();
// indicate the authed by mech in the auth context
// context.put(AuthContext.AC_AUTHED_BY_MECH, authedByMech); TODO
return;
} catch (ServiceException e) {
if (!allowFallback || authMech.isZimbraAuth())
throw e;
ZimbraLog.account.warn(authMech.getMechanism() + " auth for domain " +
domain.getName() + " failed, fall back to zimbra default auth mechanism", e);
}
// fall back to zimbra default auth
AuthMechanism.doZimbraAuth(this, domain, acct, password, context);
// context.put(AuthContext.AC_AUTHED_BY_MECH, Provisioning.AM_ZIMBRA); // TODO
}
@Override
public void changePassword(Account acct, String currentPassword, String newPassword)
throws ServiceException {
authAccount(acct, currentPassword, false, null);
boolean locked = acct.getBooleanAttr(Provisioning.A_zimbraPasswordLocked, false);
if (locked)
throw AccountServiceException.PASSWORD_LOCKED();
setPassword(acct, newPassword, true, false);
}
/**
* @param newPassword
* @throws AccountServiceException
*/
private void checkHistory(String newPassword, String[] history)
throws AccountServiceException {
if (history == null)
return;
for (int i=0; i < history.length; i++) {
int sepIndex = history[i].indexOf(':');
if (sepIndex != -1) {
String encoded = history[i].substring(sepIndex+1);
if (PasswordUtil.SSHA.verifySSHA(encoded, newPassword))
throw AccountServiceException.PASSWORD_RECENTLY_USED();
}
}
}
/**
* update password history
* @param history current history
* @param currentPassword the current encoded-password
* @param maxHistory number of prev passwords to keep
* @return new hsitory
*/
private String[] updateHistory(String history[], String currentPassword, int maxHistory) {
String[] newHistory = history;
if (currentPassword == null)
return null;
String currentHistory = System.currentTimeMillis() + ":"+currentPassword;
// just add if empty or room
if (history == null || history.length < maxHistory) {
if (history == null) {
newHistory = new String[1];
} else {
newHistory = new String[history.length+1];
System.arraycopy(history, 0, newHistory, 0, history.length);
}
newHistory[newHistory.length-1] = currentHistory;
return newHistory;
}
// remove oldest, add current
long min = Long.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < history.length; i++) {
int sepIndex = history[i].indexOf(':');
if (sepIndex == -1) {
// nuke it if no separator
minIndex = i;
break;
}
long val = Long.parseLong(history[i].substring(0, sepIndex));
if (val < min) {
min = val;
minIndex = i;
}
}
if (minIndex == -1)
minIndex = 0;
history[minIndex] = currentHistory;
return history;
}
@Override
public SetPasswordResult setPassword(Account acct, String newPassword)
throws ServiceException {
return setPassword(acct, newPassword, false);
}
@Override
public SetPasswordResult setPassword(Account acct, String newPassword,
boolean enforcePasswordPolicy)
throws ServiceException {
SetPasswordResult result = new SetPasswordResult();
String msg = null;
try {
// dry run to pick up policy violation, if any
setPassword(acct, newPassword, false, true);
} catch (ServiceException e) {
msg = e.getMessage();
}
setPassword(acct, newPassword, enforcePasswordPolicy, false);
if (msg != null) {
msg = L10nUtil.getMessage(L10nUtil.MsgKey.passwordViolation,
acct.getLocale(), acct.getName(), msg);
result.setMessage(msg);
}
return result;
}
@Override
public void checkPasswordStrength(Account acct, String password)
throws ServiceException {
checkPasswordStrength(password, acct, null, null);
}
private int getInt(Account acct, Cos cos, ZMutableEntry entry, String name, int defaultValue)
throws ServiceException {
if (acct != null) {
return acct.getIntAttr(name, defaultValue);
}
try {
String v = entry.getAttrString(name);
if (v != null) {
try {
return Integer.parseInt(v);
} catch (NumberFormatException e) {
return defaultValue;
}
}
} catch (ServiceException ne) {
throw ServiceException.FAILURE(ne.getMessage(), ne);
}
return cos.getIntAttr(name, defaultValue);
}
private String getString(Account acct, Cos cos, ZMutableEntry entry, String name)
throws ServiceException {
if (acct != null) {
return acct.getAttr(name);
}
try {
String v = entry.getAttrString(name);
if (v != null) {
return v;
}
} catch (ServiceException ne) {
throw ServiceException.FAILURE(ne.getMessage(), ne);
}
return cos.getAttr(name);
}
/**
* called to check password strength. Should pass in either an Account, or Cos/Attributes (during creation).
*
* @param password
* @param acct
* @param cos
* @param attrs
* @throws ServiceException
*/
private void checkPasswordStrength(String password, Account acct, Cos cos, ZMutableEntry entry)
throws ServiceException {
int minLength = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinLength, 0);
if (minLength > 0 && password.length() < minLength) {
throw AccountServiceException.INVALID_PASSWORD("too short",
new Argument(Provisioning.A_zimbraPasswordMinLength, minLength, Argument.Type.NUM));
}
int maxLength = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMaxLength, 0);
if (maxLength > 0 && password.length() > maxLength) {
throw AccountServiceException.INVALID_PASSWORD("too long",
new Argument(Provisioning.A_zimbraPasswordMaxLength, maxLength, Argument.Type.NUM));
}
int minUpperCase = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinUpperCaseChars, 0);
int minLowerCase = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinLowerCaseChars, 0);
int minNumeric = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinNumericChars, 0);
int minPunctuation = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinPunctuationChars, 0);
int minAlpha = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinAlphaChars, 0);
int minNumOrPunc = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinDigitsOrPuncs, 0);
String allowedChars = getString(acct, cos, entry, Provisioning.A_zimbraPasswordAllowedChars);
Pattern allowedCharsPattern = null;
if (allowedChars != null) {
try {
allowedCharsPattern = Pattern.compile(allowedChars);
} catch (PatternSyntaxException e) {
throw AccountServiceException.INVALID_PASSWORD(Provisioning.A_zimbraPasswordAllowedChars +
" is not valid regex: " + e.getMessage());
}
}
String allowedPuncChars = getString(acct, cos, entry, Provisioning.A_zimbraPasswordAllowedPunctuationChars);
Pattern allowedPuncCharsPattern = null;
if (allowedPuncChars != null) {
try {
allowedPuncCharsPattern = Pattern.compile(allowedPuncChars);
} catch (PatternSyntaxException e) {
throw AccountServiceException.INVALID_PASSWORD(Provisioning.A_zimbraPasswordAllowedPunctuationChars +
" is not valid regex: " + e.getMessage());
}
}
boolean hasPolicies = minUpperCase > 0 || minLowerCase > 0 || minNumeric > 0 || minPunctuation > 0 ||
minAlpha > 0 || minNumOrPunc > 0 || allowedCharsPattern != null || allowedPuncCharsPattern != null;
if (!hasPolicies) {
return;
}
int upper = 0;
int lower = 0;
int numeric = 0;
int punctuation = 0;
int alpha = 0;
for (int i=0; i < password.length(); i++) {
char ch = password.charAt(i);
if (allowedCharsPattern != null) {
if (!allowedCharsPattern.matcher(Character.toString(ch)).matches()) {
throw AccountServiceException.INVALID_PASSWORD(ch + " is not an allowed character",
new Argument(Provisioning.A_zimbraPasswordAllowedChars, allowedChars, Argument.Type.STR));
}
}
boolean isAlpha = true;
if (Character.isUpperCase(ch)) {
upper++;
} else if (Character.isLowerCase(ch)) {
lower++;
} else if (Character.isDigit(ch)) {
numeric++;
isAlpha = false;
} else if (allowedPuncCharsPattern != null) {
if (allowedPuncCharsPattern.matcher(Character.toString(ch)).matches()) {
punctuation++;
isAlpha = false;
}
} else if (isAsciiPunc(ch)) {
punctuation++;
isAlpha = false;
}
if (isAlpha) {
alpha++;
}
}
if (upper < minUpperCase) {
throw AccountServiceException.INVALID_PASSWORD("not enough upper case characters",
new Argument(Provisioning.A_zimbraPasswordMinUpperCaseChars, minUpperCase, Argument.Type.NUM));
}
if (lower < minLowerCase) {
throw AccountServiceException.INVALID_PASSWORD("not enough lower case characters",
new Argument(Provisioning.A_zimbraPasswordMinLowerCaseChars, minLowerCase, Argument.Type.NUM));
}
if (numeric < minNumeric) {
throw AccountServiceException.INVALID_PASSWORD("not enough numeric characters",
new Argument(Provisioning.A_zimbraPasswordMinNumericChars, minNumeric, Argument.Type.NUM));
}
if (punctuation < minPunctuation) {
throw AccountServiceException.INVALID_PASSWORD("not enough punctuation characters",
new Argument(Provisioning.A_zimbraPasswordMinPunctuationChars, minPunctuation, Argument.Type.NUM));
}
if (alpha < minAlpha) {
throw AccountServiceException.INVALID_PASSWORD("not enough alpha characters",
new Argument(Provisioning.A_zimbraPasswordMinAlphaChars, minAlpha, Argument.Type.NUM));
}
if (numeric + punctuation < minNumOrPunc) {
throw AccountServiceException.INVALID_PASSWORD("not enough numeric or punctuation characters",
new Argument(Provisioning.A_zimbraPasswordMinDigitsOrPuncs, minNumOrPunc, Argument.Type.NUM));
}
}
private boolean isAsciiPunc(char ch) {
return
(ch >= 33 && ch <= 47) || // ! " # $ % & ' ( ) * + , - . /
(ch >= 58 && ch <= 64) || // : ; < = > ? @
(ch >= 91 && ch <= 96) || // [ \ ] ^ _ `
(ch >=123 && ch <= 126); // { | } ~
}
// called by create account
private void setInitialPassword(Cos cos, ZMutableEntry entry, String newPassword)
throws ServiceException {
String userPassword = entry.getAttrString(Provisioning.A_userPassword);
if (userPassword == null && (newPassword == null || "".equals(newPassword))) return;
if (userPassword == null) {
checkPasswordStrength(newPassword, null, cos, entry);
userPassword = PasswordUtil.SSHA.generateSSHA(newPassword, null);
}
entry.setAttr(Provisioning.A_userPassword, userPassword);
entry.setAttr(Provisioning.A_zimbraPasswordModifiedTime, DateUtil.toGeneralizedTime(new Date()));
}
void setPassword(Account acct, String newPassword, boolean enforcePolicy, boolean dryRun)
throws ServiceException {
boolean mustChange = acct.getBooleanAttr(Provisioning.A_zimbraPasswordMustChange, false);
if (enforcePolicy || dryRun) {
checkPasswordStrength(newPassword, acct, null, null);
// skip min age checking if mustChange is set
if (!mustChange) {
int minAge = acct.getIntAttr(Provisioning.A_zimbraPasswordMinAge, 0);
if (minAge > 0) {
Date lastChange = acct.getGeneralizedTimeAttr(Provisioning.A_zimbraPasswordModifiedTime, null);
if (lastChange != null) {
long last = lastChange.getTime();
long curr = System.currentTimeMillis();
if ((last+(Constants.MILLIS_PER_DAY * minAge)) > curr)
throw AccountServiceException.PASSWORD_CHANGE_TOO_SOON();
}
}
}
}
Map<String, Object> attrs = new HashMap<String, Object>();
int enforceHistory = acct.getIntAttr(Provisioning.A_zimbraPasswordEnforceHistory, 0);
if (enforceHistory > 0) {
String[] newHistory = updateHistory(
acct.getMultiAttr(Provisioning.A_zimbraPasswordHistory),
acct.getAttr(Provisioning.A_userPassword),
enforceHistory);
attrs.put(Provisioning.A_zimbraPasswordHistory, newHistory);
if (enforcePolicy || dryRun)
checkHistory(newPassword, newHistory);
}
if (dryRun) {
return;
}
String encodedPassword = PasswordUtil.SSHA.generateSSHA(newPassword, null);
// unset it so it doesn't take up space...
if (mustChange)
attrs.put(Provisioning.A_zimbraPasswordMustChange, "");
attrs.put(Provisioning.A_userPassword, encodedPassword);
attrs.put(Provisioning.A_zimbraPasswordModifiedTime, DateUtil.toGeneralizedTime(new Date()));
// update the validity value to invalidate auto-standing auth tokens
int tokenValidityValue = acct.getAuthTokenValidityValue();
acct.setAuthTokenValidityValue(tokenValidityValue == Integer.MAX_VALUE ? 0 : tokenValidityValue + 1, attrs);
ChangePasswordListener.ChangePasswordListenerContext ctxts = new ChangePasswordListener.ChangePasswordListenerContext();
ChangePasswordListener.invokePreModify(acct, newPassword, ctxts, attrs);
// modify the password
modifyAttrs(acct, attrs);
ChangePasswordListener.invokePostModify(acct, newPassword, ctxts);
}
@Override
public Zimlet getZimlet(String name) throws ServiceException {
return getZimlet(name, null, true);
}
private Zimlet getFromCache(Key.ZimletBy keyType, String key) {
switch(keyType) {
case name:
return zimletCache.getByName(key);
case id:
return zimletCache.getById(key);
default:
return null;
}
}
Zimlet lookupZimlet(String name, ZLdapContext zlc) throws ServiceException {
return getZimlet(name, zlc, false);
}
private Zimlet getZimlet(String name, ZLdapContext initZlc, boolean useCache)
throws ServiceException {
LdapZimlet zimlet = null;
if (useCache) {
zimlet = zimletCache.getByName(name);
}
if (zimlet != null) {
return zimlet;
}
try {
String dn = mDIT.zimletNameToDN(name);
ZAttributes attrs = helper.getAttributes(
initZlc, LdapServerType.REPLICA, LdapUsage.GET_ZIMLET, dn, null);
zimlet = new LdapZimlet(dn, attrs, this);
if (useCache) {
ZimletUtil.reloadZimlet(name);
zimletCache.put(zimlet); // put LdapZimlet into the cache after successful ZimletUtil.reloadZimlet()
}
return zimlet;
} catch (LdapEntryNotFoundException e) {
return null;
} catch (ServiceException ne) {
throw ServiceException.FAILURE("unable to get zimlet: "+name, ne);
} catch (ZimletException ze) {
throw ServiceException.FAILURE("unable to load zimlet: "+name, ze);
}
}
@Override
public List<Zimlet> listAllZimlets() throws ServiceException {
List<Zimlet> result = new ArrayList<Zimlet>();
try {
ZSearchResultEnumeration ne = helper.searchDir(mDIT.zimletBaseDN(),
filterFactory.allZimlets(), ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapZimlet(sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all zimlets", e);
}
Collections.sort(result);
return result;
}
@Override
public Zimlet createZimlet(String name, Map<String, Object> zimletAttrs)
throws ServiceException {
name = name.toLowerCase().trim();
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(zimletAttrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_ZIMLET);
String hasKeyword = LdapConstants.LDAP_FALSE;
if (zimletAttrs.containsKey(A_zimbraZimletKeyword)) {
hasKeyword = ProvisioningConstants.TRUE;
}
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(zimletAttrs);
entry.setAttr(A_objectClass, "zimbraZimletEntry");
entry.setAttr(A_zimbraZimletEnabled, ProvisioningConstants.FALSE);
entry.setAttr(A_zimbraZimletIndexingEnabled, hasKeyword);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
String dn = mDIT.zimletNameToDN(name);
entry.setDN(dn);
zlc.createEntry(entry);
Zimlet zimlet = lookupZimlet(name, zlc);
AttributeManager.getInstance().postModify(zimletAttrs, zimlet, callbackContext);
return zimlet;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.ZIMLET_EXISTS(name);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create zimlet: "+name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteZimlet(String name) throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_ZIMLET);
LdapZimlet zimlet = (LdapZimlet)getZimlet(name, zlc, true);
if (zimlet != null) {
zimletCache.remove(zimlet);
zlc.deleteEntry(zimlet.getDN());
}
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to delete zimlet: "+name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public CalendarResource createCalendarResource(String emailAddress,String password,
Map<String, Object> calResAttrs)
throws ServiceException {
emailAddress = emailAddress.toLowerCase().trim();
calResAttrs.put(Provisioning.A_zimbraAccountCalendarUserType,
AccountCalendarUserType.RESOURCE.toString());
SpecialAttrs specialAttrs = mDIT.handleSpecialAttrs(calResAttrs);
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
Set<String> ocs = LdapObjectClass.getCalendarResourceObjectClasses(this);
Account acct = createAccount(emailAddress, password, calResAttrs, specialAttrs,
ocs.toArray(new String[0]), false, null);
LdapCalendarResource resource =
(LdapCalendarResource) getCalendarResourceById(acct.getId(), true);
AttributeManager.getInstance().
postModify(calResAttrs, resource, callbackContext);
return resource;
}
@Override
public void deleteCalendarResource(String zimbraId)
throws ServiceException {
deleteAccount(zimbraId);
}
@Override
public void renameCalendarResource(String zimbraId, String newName)
throws ServiceException {
renameAccount(zimbraId, newName);
}
@Override
public CalendarResource get(Key.CalendarResourceBy keyType, String key)
throws ServiceException {
return get(keyType, key, false);
}
@Override
public CalendarResource get(Key.CalendarResourceBy keyType, String key, boolean loadFromMaster)
throws ServiceException {
switch(keyType) {
case id:
return getCalendarResourceById(key, loadFromMaster);
case foreignPrincipal:
return getCalendarResourceByForeignPrincipal(key, loadFromMaster);
case name:
return getCalendarResourceByName(key, loadFromMaster);
default:
return null;
}
}
private CalendarResource getCalendarResourceById(String zimbraId, boolean loadFromMaster)
throws ServiceException {
if (zimbraId == null)
return null;
Account acct = accountCache.getById(zimbraId);
if (acct != null) {
if (acct instanceof LdapCalendarResource) {
return (LdapCalendarResource) acct;
} else {
// could be a non-resource Account
return null;
}
}
LdapCalendarResource resource = (LdapCalendarResource) getAccountByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.calendarResourceById(zimbraId),
null, loadFromMaster);
accountCache.put(resource);
return resource;
}
private CalendarResource getCalendarResourceByName(String emailAddress, boolean loadFromMaster)
throws ServiceException {
emailAddress = fixupAccountName(emailAddress);
Account acct = accountCache.getByName(emailAddress);
if (acct != null) {
if (acct instanceof LdapCalendarResource) {
return (LdapCalendarResource) acct;
} else {
// could be a non-resource Account
return null;
}
}
LdapCalendarResource resource = (LdapCalendarResource) getAccountByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.calendarResourceByName(emailAddress),
null, loadFromMaster);
accountCache.put(resource);
return resource;
}
private CalendarResource getCalendarResourceByForeignPrincipal(String foreignPrincipal, boolean loadFromMaster)
throws ServiceException {
LdapCalendarResource resource =
(LdapCalendarResource) getAccountByQuery(
mDIT.mailBranchBaseDN(),
filterFactory.calendarResourceByForeignPrincipal(foreignPrincipal),
null, loadFromMaster);
accountCache.put(resource);
return resource;
}
private Account makeAccount(String dn, ZAttributes attrs) throws ServiceException {
return makeAccount(dn, attrs, null);
}
private Account makeAccountNoDefaults(String dn, ZAttributes attrs) throws ServiceException {
return makeAccount(dn, attrs, MakeObjectOpt.NO_DEFAULTS);
}
private Account makeAccount(String dn, ZAttributes attrs, MakeObjectOpt makeObjOpt)
throws ServiceException {
String userType = attrs.getAttrString(Provisioning.A_zimbraAccountCalendarUserType);
boolean isAccount = (userType == null) || userType.equals(AccountCalendarUserType.USER.toString());
String emailAddress = attrs.getAttrString(Provisioning.A_zimbraMailDeliveryAddress);
if (emailAddress == null)
emailAddress = mDIT.dnToEmail(dn, attrs);
Account acct = (isAccount) ? new LdapAccount(dn, emailAddress, attrs, null, this) :
new LdapCalendarResource(dn, emailAddress, attrs, null, this);
setAccountDefaults(acct, makeObjOpt);
return acct;
}
private void setAccountDefaults(Account acct, MakeObjectOpt makeObjOpt)
throws ServiceException {
if (makeObjOpt == MakeObjectOpt.NO_DEFAULTS) {
// don't set any default
} else if (makeObjOpt == MakeObjectOpt.NO_SECONDARY_DEFAULTS) {
acct.setAccountDefaults(false);
} else {
acct.setAccountDefaults(true);
}
}
private Alias makeAlias(String dn, ZAttributes attrs) throws ServiceException {
String emailAddress = mDIT.dnToEmail(dn, attrs);
Alias alias = new LdapAlias(dn, emailAddress, attrs, this);
return alias;
}
private DistributionList makeDistributionList(String dn, ZAttributes attrs, boolean isBasic)
throws ServiceException {
String emailAddress = mDIT.dnToEmail(dn, attrs);
DistributionList dl = new LdapDistributionList(dn, emailAddress, attrs, isBasic, this);
return dl;
}
private DynamicGroup makeDynamicGroup(ZLdapContext initZlc, String dn, ZAttributes attrs)
throws ServiceException {
String emailAddress = mDIT.dnToEmail(dn, mDIT.dynamicGroupNamingRdnAttr(), attrs);
LdapDynamicGroup group = new LdapDynamicGroup(dn, emailAddress, attrs, this);
if (group.isIsACLGroup()) {
// load dynamic unit
String dynamicUnitDN = mDIT.dynamicGroupUnitNameToDN(
DYNAMIC_GROUP_DYNAMIC_UNIT_NAME, dn);
ZAttributes dynamicUnitAttrs = helper.getAttributes(
initZlc, LdapServerType.REPLICA, LdapUsage.GET_GROUP_UNIT, dynamicUnitDN, null);
LdapDynamicGroup.DynamicUnit dynamicUnit = new LdapDynamicGroup.DynamicUnit(
dynamicUnitDN, DYNAMIC_GROUP_DYNAMIC_UNIT_NAME, dynamicUnitAttrs, this);
// load static unit
String staticUnitDN = mDIT.dynamicGroupUnitNameToDN(
DYNAMIC_GROUP_STATIC_UNIT_NAME, dn);
ZAttributes staticUnitAttrs = helper.getAttributes(
initZlc, LdapServerType.REPLICA, LdapUsage.GET_GROUP_UNIT, staticUnitDN, null);
LdapDynamicGroup.StaticUnit staticUnit = new LdapDynamicGroup.StaticUnit(
staticUnitDN, DYNAMIC_GROUP_STATIC_UNIT_NAME, staticUnitAttrs, this);
group.setSubUnits(dynamicUnit, staticUnit);
}
return group;
}
/**
* called when an account/dl is renamed
*
*/
protected void renameAddressesInAllDistributionLists(String oldName, String newName,
ReplaceAddressResult replacedAliasPairs) {
Map<String, String> changedPairs = new HashMap<String, String>();
changedPairs.put(oldName, newName);
for (int i=0 ; i < replacedAliasPairs.oldAddrs().length; i++) {
String oldAddr = replacedAliasPairs.oldAddrs()[i];
String newAddr = replacedAliasPairs.newAddrs()[i];
if (!oldAddr.equals(newAddr)) {
changedPairs.put(oldAddr, newAddr);
}
}
renameAddressesInAllDistributionLists(changedPairs);
}
protected void renameAddressesInAllDistributionLists(Map<String, String> changedPairs) {
String oldAddrs[] = changedPairs.keySet().toArray(new String[0]);
String newAddrs[] = changedPairs.values().toArray(new String[0]);
List<DistributionList> lists = null;
Map<String, String[]> attrs = null;
try {
lists = getAllDistributionListsForAddresses(oldAddrs, false);
} catch (ServiceException se) {
ZimbraLog.account.warn("unable to rename addr "+oldAddrs.toString()+" in all DLs ", se);
return;
}
for (DistributionList list: lists) {
// should we just call removeMember/addMember? This might be quicker, because calling
// removeMember/addMember might have to update an entry's zimbraMemberId twice
if (attrs == null) {
attrs = new HashMap<String, String[]>();
attrs.put("-" + Provisioning.A_zimbraMailForwardingAddress, oldAddrs);
attrs.put("+" + Provisioning.A_zimbraMailForwardingAddress, newAddrs);
}
try {
modifyAttrs(list, attrs);
//list.removeMember(oldName)
//list.addMember(newName);
} catch (ServiceException se) {
// log warning an continue
ZimbraLog.account.warn("unable to rename "+oldAddrs.toString()+" to " +
newAddrs.toString()+" in DL "+list.getName(), se);
}
}
}
/**
* called when an account is being deleted. swallows all exceptions (logs warnings).
*/
void removeAddressFromAllDistributionLists(String address) {
String addrs[] = new String[] { address } ;
removeAddressesFromAllDistributionLists(addrs);
}
/**
* called when an account is being deleted or status being set to closed. swallows all exceptions (logs warnings).
*/
public void removeAddressesFromAllDistributionLists(String[] addrs) {
List<DistributionList> lists = null;
try {
lists = getAllDistributionListsForAddresses(addrs, false);
} catch (ServiceException se) {
StringBuilder sb = new StringBuilder();
for (String addr : addrs)
sb.append(addr + ", ");
ZimbraLog.account.warn("unable to get all DLs for addrs " + sb.toString());
return;
}
for (DistributionList list: lists) {
try {
removeMembers(list, addrs);
} catch (ServiceException se) {
// log warning and continue
StringBuilder sb = new StringBuilder();
for (String addr : addrs)
sb.append(addr + ", ");
ZimbraLog.account.warn("unable to remove "+sb.toString()+" from DL "+list.getName(), se);
}
}
}
@SuppressWarnings("unchecked")
private List<DistributionList> getAllDistributionListsForAddresses(String addrs[],
boolean basicAttrsOnly)
throws ServiceException {
if (addrs == null || addrs.length == 0)
return new ArrayList<DistributionList>();
String [] attrs = basicAttrsOnly ? BASIC_DL_ATTRS : null;
SearchDirectoryOptions searchOpts = new SearchDirectoryOptions(attrs);
searchOpts.setFilter(filterFactory.distributionListsByMemberAddrs(addrs));
searchOpts.setTypes(ObjectType.distributionlists);
searchOpts.setSortOpt(SortOpt.SORT_ASCENDING);
return (List<DistributionList>) searchDirectoryInternal(searchOpts);
}
private List<DistributionList> getAllDirectDLs(LdapProvisioning prov, Entry entry)
throws ServiceException {
if (!(entry instanceof GroupedEntry)) {
throw ServiceException.FAILURE("internal error", null);
}
EntryCacheDataKey cacheKey = EntryCacheDataKey.GROUPEDENTRY_DIRECT_GROUPIDS;
@SuppressWarnings("unchecked")
List<String> directGroupIds = (List<String>) entry.getCachedData(cacheKey);
List<DistributionList> directGroups = null;
if (directGroupIds == null) {
String[] addrs = ((GroupedEntry)entry).getAllAddrsAsGroupMember();
// fetch from LDAP
directGroups = prov.getAllDistributionListsForAddresses(addrs, true);
// - build the group id list and cache it on the entry
// - add each group in cache only if it is not already in.
// we do not want to overwrite the entry in cache, because it
// might already have all its direct group ids cached on it.
// - if the group is already in cache, return the cached instance
// instead of the instance we just fetched, because the cached
// instance might have its direct group ids cached on it.
directGroupIds = new ArrayList<String>(directGroups.size());
List<DistributionList> directGroupsToReturn = new ArrayList<DistributionList>(directGroups.size());
for (DistributionList group : directGroups) {
String groupId = group.getId();
directGroupIds.add(groupId);
DistributionList cached = getDLFromCache(Key.DistributionListBy.id, groupId);
if (cached == null) {
putInGroupCache(group);
directGroupsToReturn.add(group);
} else {
directGroupsToReturn.add(cached);
}
}
entry.setCachedData(cacheKey, directGroupIds);
return directGroupsToReturn;
} else {
/*
* The entry already have direct group ids cached.
* Go through each of them and fetch the groups,
* eithr from cache or from LDAP (prov.getDLBasic).
*/
directGroups = new ArrayList<DistributionList>();
Set<String> idsToRemove = null;
for (String groupId : directGroupIds) {
DistributionList group = prov.getDLBasic(Key.DistributionListBy.id, groupId);
if (group == null) {
// the group could have been deleted
// remove it from our direct group id cache on the entry
if (idsToRemove == null) {
idsToRemove = new HashSet<String>();
}
idsToRemove.add(groupId);
} else {
directGroups.add(group);
}
}
// update our direct group id cache if needed
if (idsToRemove != null) {
// create a new object, do *not* update directly on the cached copy
List<String> updatedDirectGroupIds = new ArrayList<String>();
for (String id : directGroupIds) {
if (!idsToRemove.contains(id)) {
updatedDirectGroupIds.add(id);
}
}
// swap in the new data
entry.setCachedData(cacheKey, updatedDirectGroupIds);
}
}
return directGroups;
}
/*
* like get(DistributionListBy keyType, String key)
* the difference are:
* - cached
* - entry returned only contains minimal DL attrs
* - entry returned does not contain members (zimbraMailForwardingAddress)
*/
@Override
public DistributionList getDLBasic(Key.DistributionListBy keyType, String key)
throws ServiceException {
return getDLBasic(keyType, key, null);
}
private DistributionList getDLBasic(Key.DistributionListBy keyType, String key,
ZLdapContext zlc)
throws ServiceException {
Group group = getGroupFromCache(keyType, key);
if (group instanceof DistributionList) {
return (DistributionList) group;
} else if (group instanceof DynamicGroup) {
return null;
}
// not in cache, fetch from LDAP
DistributionList dl = null;
switch(keyType) {
case id:
dl = getDistributionListByQuery(mDIT.mailBranchBaseDN(),
filterFactory.distributionListById(key), zlc, true);
break;
case name:
dl = getDistributionListByQuery(mDIT.mailBranchBaseDN(),
filterFactory.distributionListByName(key), zlc, true);
break;
default:
return null;
}
if (dl != null) {
putInGroupCache(dl);
}
return dl;
}
private List<DistributionList> getContainingDistributionLists(Entry entry,
boolean directOnly, Map<String, String> via)
throws ServiceException {
List<DistributionList> directDLs = getAllDirectDLs(this, entry);
HashSet<String> directDLSet = new HashSet<String>();
HashSet<String> checked = new HashSet<String>();
List<DistributionList> result = new ArrayList<DistributionList>();
Stack<DistributionList> dlsToCheck = new Stack<DistributionList>();
for (DistributionList dl : directDLs) {
dlsToCheck.push(dl);
directDLSet.add(dl.getName());
}
while (!dlsToCheck.isEmpty()) {
DistributionList dl = dlsToCheck.pop();
if (checked.contains(dl.getId())) continue;
result.add(dl);
checked.add(dl.getId());
if (directOnly) continue;
List<DistributionList> newLists = getAllDirectDLs(this, dl);
for (DistributionList newDl: newLists) {
if (!directDLSet.contains(newDl.getName())) {
if (via != null) {
via.put(newDl.getName(), dl.getName());
}
dlsToCheck.push(newDl);
}
}
}
Collections.sort(result);
return result;
}
@Override
public Set<String> getDistributionLists(Account acct) throws ServiceException {
@SuppressWarnings("unchecked")
Set<String> dls = (Set<String>) acct.getCachedData(EntryCacheDataKey.ACCOUNT_DLS);
if (dls != null) {
return dls;
}
dls = getDistributionListIds(acct, false);
acct.setCachedData(EntryCacheDataKey.ACCOUNT_DLS, dls);
return dls;
}
@Override
public Set<String> getDirectDistributionLists(Account acct) throws ServiceException {
@SuppressWarnings("unchecked")
Set<String> dls = (Set<String>) acct.getCachedData(EntryCacheDataKey.ACCOUNT_DIRECT_DLS);
if (dls != null) {
return dls;
}
dls = getDistributionListIds(acct, true);
acct.setCachedData(EntryCacheDataKey.ACCOUNT_DIRECT_DLS, dls);
return dls;
}
private Set<String> getDistributionListIds(Account acct, boolean directOnly)
throws ServiceException {
Set<String> dls = new HashSet<String>();
List<DistributionList> lists = getDistributionLists(acct, directOnly, null);
for (DistributionList dl : lists) {
dls.add(dl.getId());
}
dls = Collections.unmodifiableSet(dls);
return dls;
}
@Override
public boolean inDistributionList(Account acct, String zimbraId) throws ServiceException {
return getDistributionLists(acct).contains(zimbraId);
}
@Override
public boolean inDistributionList(DistributionList list, String zimbraId)
throws ServiceException {
GroupMembership groupMembership = getGroupMembership(list, false);
return groupMembership.groupIds().contains(zimbraId);
}
@Override
public List<DistributionList> getDistributionLists(Account acct, boolean directOnly,
Map<String, String> via) throws ServiceException {
return getContainingDistributionLists(acct, directOnly, via);
}
private static final int DEFAULT_GAL_MAX_RESULTS = 100;
private static final String DATA_GAL_RULES = "GAL_RULES";
@Override
public List<?> getAllAccounts(Domain domain) throws ServiceException {
SearchAccountsOptions opts = new SearchAccountsOptions(domain);
opts.setFilter(filterFactory.allAccountsOnly());
opts.setIncludeType(IncludeType.ACCOUNTS_ONLY);
opts.setSortOpt(SortOpt.SORT_ASCENDING);
return searchDirectory(opts);
}
@Override
public void getAllAccounts(Domain domain, NamedEntry.Visitor visitor)
throws ServiceException {
SearchAccountsOptions opts = new SearchAccountsOptions(domain);
opts.setFilter(filterFactory.allAccountsOnly());
opts.setIncludeType(IncludeType.ACCOUNTS_ONLY);
searchDirectory(opts, visitor);
}
@Override
public void getAllAccounts(Domain domain, Server server, NamedEntry.Visitor visitor)
throws ServiceException {
if (server != null) {
SearchAccountsOptions searchOpts = new SearchAccountsOptions(domain);
searchOpts.setIncludeType(IncludeType.ACCOUNTS_ONLY);
searchAccountsOnServerInternal(server, searchOpts, visitor);
} else {
getAllAccounts(domain, visitor);
}
}
@Override
public List<?> getAllCalendarResources(Domain domain) throws ServiceException {
SearchDirectoryOptions searchOpts = new SearchDirectoryOptions(domain);
searchOpts.setFilter(mDIT.filterCalendarResourcesByDomain(domain));
searchOpts.setTypes(ObjectType.resources);
searchOpts.setSortOpt(SortOpt.SORT_ASCENDING);
return searchDirectoryInternal(searchOpts);
}
@Override
public void getAllCalendarResources(Domain domain, NamedEntry.Visitor visitor)
throws ServiceException {
SearchDirectoryOptions searchOpts = new SearchDirectoryOptions(domain);
searchOpts.setFilter(mDIT.filterCalendarResourcesByDomain(domain));
searchOpts.setTypes(ObjectType.resources);
searchDirectoryInternal(searchOpts, visitor);
}
@Override
public void getAllCalendarResources(Domain domain, Server server, NamedEntry.Visitor visitor)
throws ServiceException {
if (server != null) {
SearchAccountsOptions searchOpts = new SearchAccountsOptions(domain);
searchOpts.setIncludeType(IncludeType.CALENDAR_RESOURCES_ONLY);
searchAccountsOnServerInternal(server, searchOpts, visitor);
} else {
getAllCalendarResources(domain, visitor);
}
}
@Override
public List<?> getAllDistributionLists(Domain domain) throws ServiceException {
SearchDirectoryOptions searchOpts = new SearchDirectoryOptions(domain);
searchOpts.setFilter(mDIT.filterDistributionListsByDomain(domain));
searchOpts.setTypes(ObjectType.distributionlists);
searchOpts.setSortOpt(SortOpt.SORT_ASCENDING);
return searchDirectoryInternal(searchOpts);
}
@Override
public SearchGalResult autoCompleteGal(Domain domain, String query,
GalSearchType type, int limit, GalContact.Visitor visitor)
throws ServiceException {
SearchGalResult searchResult = SearchGalResult.newSearchGalResult(visitor);
GalSearchParams params = new GalSearchParams(domain, null);
params.setQuery(query);
params.setType(type);
params.setOp(GalOp.autocomplete);
params.setLimit(limit);
params.setGalResult(searchResult);
LdapOnlyGalSearchResultCallback callback =
new LdapOnlyGalSearchResultCallback(params, visitor);
params.setResultCallback(callback);
GalSearchControl gal = new GalSearchControl(params);
gal.ldapSearch();
// Collections.sort(searchResult.getMatches()); sort?
return searchResult;
}
@Override
public SearchGalResult searchGal(Domain domain, String query, GalSearchType type,
int limit, GalContact.Visitor visitor)
throws ServiceException {
SearchGalResult searchResult = SearchGalResult.newSearchGalResult(visitor);
GalSearchParams params = new GalSearchParams(domain, null);
params.setQuery(query);
params.setType(type);
params.setOp(GalOp.search);
params.setLimit(limit);
params.setGalResult(searchResult);
LdapOnlyGalSearchResultCallback callback =
new LdapOnlyGalSearchResultCallback(params, visitor);
params.setResultCallback(callback);
GalSearchControl gal = new GalSearchControl(params);
gal.ldapSearch();
return searchResult;
}
@Override
public SearchGalResult syncGal(Domain domain, String token, GalContact.Visitor visitor)
throws ServiceException {
SearchGalResult searchResult = SearchGalResult.newSearchGalResult(visitor);
GalSearchParams params = new GalSearchParams(domain, null);
params.setQuery("");
params.setToken(token);
params.setType(GalSearchType.all);
params.setOp(GalOp.sync);
params.setFetchGroupMembers(true);
params.setNeedSMIMECerts(true);
params.setGalResult(searchResult);
LdapOnlyGalSearchResultCallback callback =
new LdapOnlyGalSearchResultCallback(params, visitor);
params.setResultCallback(callback);
GalSearchControl gal = new GalSearchControl(params);
gal.ldapSearch();
return searchResult;
}
private static class LdapOnlyGalSearchResultCallback extends GalSearchResultCallback {
GalContact.Visitor visitor;
String newToken;
boolean hasMore;
LdapOnlyGalSearchResultCallback(GalSearchParams params, GalContact.Visitor visitor) {
super(params);
this.visitor = visitor;
}
private String getNewToken() {
return newToken;
}
@Override
public void reset(GalSearchParams params) {
// do nothing
}
@Override
public void visit(GalContact c) throws ServiceException {
visitor.visit(c);
}
@Override
public void setNewToken(String newToken) {
this.newToken = newToken;
}
@Override
public void setHasMoreResult(boolean more) {
this.hasMore = hasMore;
}
@Override
public void setGalDefinitionLastModified(String timestamp) {
// do nothing
}
@Override
public Element getResponse() {
throw new UnsupportedOperationException();
}
@Override
public boolean passThruProxiedGalAcctResponse() {
throw new UnsupportedOperationException();
}
@Override
public void handleProxiedResponse(Element resp) {
throw new UnsupportedOperationException();
}
@Override
public void setNewToken(GalSyncToken newToken) {
throw new UnsupportedOperationException();
}
@Override
public void setSortBy(String sortBy) {
throw new UnsupportedOperationException();
}
@Override
public void setQueryOffset(int offset) {
throw new UnsupportedOperationException();
}
}
@Override
public void searchGal(GalSearchParams params) throws ServiceException {
LdapGalSearch.galSearch(params);
}
@Override
public SearchGalResult searchGal(Domain d,
String n,
GalSearchType type,
GalMode galMode,
String token) throws ServiceException {
return searchGal(d, n, type, galMode, token, null);
}
private SearchGalResult searchGal(Domain d,
String n,
GalSearchType type,
GalMode galMode,
String token,
GalContact.Visitor visitor)
throws ServiceException {
GalOp galOp = token != null ? GalOp.sync : GalOp.search;
// escape user-supplied string
n = LdapUtil.escapeSearchFilterArg(n);
int maxResults = token != null ? 0 : d.getIntAttr(Provisioning.A_zimbraGalMaxResults, DEFAULT_GAL_MAX_RESULTS);
if (type == GalSearchType.resource)
return searchResourcesGal(d, n, maxResults, token, galOp, visitor);
else if (type == GalSearchType.group)
return searchGroupsGal(d, n, maxResults, null, galOp, null);
GalMode mode = galMode != null ? galMode : GalMode.fromString(d.getAttr(Provisioning.A_zimbraGalMode));
SearchGalResult results = null;
if (mode == null || mode == GalMode.zimbra) {
results = searchZimbraGal(d, n, maxResults, token, galOp, visitor);
} else if (mode == GalMode.ldap) {
results = searchLdapGal(d, n, maxResults, token, galOp, visitor);
} else if (mode == GalMode.both) {
results = searchZimbraGal(d, n, maxResults/2, token, galOp, visitor);
SearchGalResult ldapResults = searchLdapGal(d, n, maxResults/2, token, galOp, visitor);
if (ldapResults != null) {
results.addMatches(ldapResults);
results.setToken(LdapUtil.getLaterTimestamp(results.getToken(), ldapResults.getToken()));
}
} else {
results = searchZimbraGal(d, n, maxResults, token, galOp, visitor);
}
if (results == null) results = SearchGalResult.newSearchGalResult(visitor); // should really not be null by now
if (type == GalSearchType.all) {
SearchGalResult resourceResults = null;
if (maxResults == 0)
resourceResults = searchResourcesGal(d, n, 0, token, galOp, visitor);
else {
int room = maxResults - results.getNumMatches();
if (room > 0)
resourceResults = searchResourcesGal(d, n, room, token, galOp, visitor);
}
if (resourceResults != null) {
results.addMatches(resourceResults);
results.setToken(LdapUtil.getLaterTimestamp(results.getToken(), resourceResults.getToken()));
}
}
return results;
}
public static String getFilterDef(String name) throws ServiceException {
String queryExprs[] = Provisioning.getInstance().getConfig().getMultiAttr(Provisioning.A_zimbraGalLdapFilterDef);
String fname = name+":";
String queryExpr = null;
for (int i=0; i < queryExprs.length; i++) {
if (queryExprs[i].startsWith(fname)) {
queryExpr = queryExprs[i].substring(fname.length());
}
}
if (queryExpr == null)
ZimbraLog.gal.warn("missing filter def " + name + " in " + Provisioning.A_zimbraGalLdapFilterDef);
return queryExpr;
}
private synchronized LdapGalMapRules getGalRules(Domain d, boolean isZimbraGal) {
LdapGalMapRules rules = (LdapGalMapRules) d.getCachedData(DATA_GAL_RULES);
if (rules == null) {
rules = new LdapGalMapRules(d, isZimbraGal);
d.setCachedData(DATA_GAL_RULES, rules);
}
return rules;
}
private SearchGalResult searchResourcesGal(Domain d, String n, int maxResults, String token, GalOp galOp, GalContact.Visitor visitor)
throws ServiceException {
return searchZimbraWithNamedFilter(d, galOp, GalNamedFilter.getZimbraCalendarResourceFilter(galOp), n, maxResults, token, visitor);
}
private SearchGalResult searchGroupsGal(Domain d, String n, int maxResults, String token, GalOp galOp, GalContact.Visitor visitor)
throws ServiceException {
return searchZimbraWithNamedFilter(d, galOp, GalNamedFilter.getZimbraGroupFilter(galOp), n, maxResults, token, visitor);
}
private SearchGalResult searchZimbraGal(Domain d, String n, int maxResults, String token, GalOp galOp, GalContact.Visitor visitor)
throws ServiceException {
return searchZimbraWithNamedFilter(d, galOp, GalNamedFilter.getZimbraAcountFilter(galOp), n, maxResults, token, visitor);
}
private SearchGalResult searchZimbraWithNamedFilter(
Domain domain,
GalOp galOp,
String filterName,
String n,
int maxResults,
String token,
GalContact.Visitor visitor)
throws ServiceException {
GalParams.ZimbraGalParams galParams = new GalParams.ZimbraGalParams(domain, galOp);
String queryExpr = getFilterDef(filterName);
String query = null;
String tokenize = GalUtil.tokenizeKey(galParams, galOp);
if (queryExpr != null) {
if (token != null)
n = "";
query = GalUtil.expandFilter(tokenize, queryExpr, n, token);
}
SearchGalResult result = SearchGalResult.newSearchGalResult(visitor);
result.setTokenizeKey(tokenize);
if (query == null) {
ZimbraLog.gal.warn("searchZimbraWithNamedFilter query is null");
return result;
}
// filter out hidden entries
if (!query.startsWith("(")) {
query = "(" + query + ")";
}
query = "(&"+query+"(!(zimbraHideInGal=TRUE)))";
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapUsage.fromGalOpLegacy(galOp));
LdapGalSearch.searchGal(zlc,
GalSearchConfig.GalType.zimbra,
galParams.pageSize(),
galParams.searchBase(),
query,
maxResults,
getGalRules(domain, true),
token,
result);
} finally {
LdapClient.closeContext(zlc);
}
//Collections.sort(result);
return result;
}
private SearchGalResult searchLdapGal(Domain domain,
String n,
int maxResults,
String token,
GalOp galOp,
GalContact.Visitor visitor)
throws ServiceException {
GalParams.ExternalGalParams galParams = new GalParams.ExternalGalParams(domain, galOp);
LdapGalMapRules rules = getGalRules(domain, false);
try {
return LdapGalSearch.searchLdapGal(galParams,
galOp,
n,
maxResults,
rules,
token,
visitor);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to search GAL", e);
}
}
@Override
public void addMembers(DistributionList list, String[] members) throws ServiceException {
LdapDistributionList ldl = (LdapDistributionList) list;
addDistributionListMembers(ldl, members);
}
@Override
public void removeMembers(DistributionList list, String[] members) throws ServiceException {
LdapDistributionList ldl = (LdapDistributionList) list;
removeDistributionListMembers(ldl, members);
}
private void addDistributionListMembers(DistributionList dl, String[] members)
throws ServiceException {
Set<String> existing = dl.getMultiAttrSet(Provisioning.A_zimbraMailForwardingAddress);
Set<String> mods = new HashSet<String>();
// all addrs of this DL
AddrsOfEntry addrsOfDL = getAllAddressesOfEntry(dl.getName());
for (int i = 0; i < members.length; i++) {
String memberName = members[i].toLowerCase();
memberName = IDNUtil.toAsciiEmail(memberName);
if (addrsOfDL.isIn(memberName))
throw ServiceException.INVALID_REQUEST("Cannot add self as a member: " + memberName, null);
// cannot add a dynamic group as member
if (getDynamicGroupBasic(Key.DistributionListBy.name, memberName, null) != null) {
throw ServiceException.INVALID_REQUEST("Cannot add dynamic group as a member: " + memberName, null);
}
if (!existing.contains(memberName)) {
mods.add(memberName);
// clear the DL cache on accounts/dl
// can't do prov.getFromCache because it only caches by primary name
Account acct = get(AccountBy.name, memberName);
if (acct != null) {
clearUpwardMembershipCache(acct);
} else {
// for DistributionList/ACLGroup, get it from cache because
// if the dl is not in cache, after loading it prov.getAclGroup
// always compute the upward membership. Sounds silly if we are
// about to clean the cache. If memberName is indeed an alias
// of one of the cached DL/ACLGroup, it will get expired after 15
// mins, just like the multi-node case.
//
// Note: do not call clearUpwardMembershipCache for AclGroup because
// the upward membership cache for that is computed and cache only when
// the entry is loaded/being cached, instead of lazily computed like we
// do for account.
removeGroupFromCache(Key.DistributionListBy.name, memberName);
}
}
}
if (mods.isEmpty()) {
// nothing to do...
return;
}
PermissionCache.invalidateCache();
cleanGroupMembersCache(dl);
Map<String,String[]> modmap = new HashMap<String,String[]>();
modmap.put("+" + Provisioning.A_zimbraMailForwardingAddress, mods.toArray(new String[0]));
modifyAttrs(dl, modmap, true);
}
private void removeDistributionListMembers(DistributionList dl, String[] members)
throws ServiceException {
Set<String> curMembers = dl.getMultiAttrSet(Provisioning.A_zimbraMailForwardingAddress);
// bug 46219, need a case insentitive Set
Set<String> existing = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
existing.addAll(curMembers);
Set<String> mods = new HashSet<String>();
HashSet<String> failed = new HashSet<String>();
for (int i = 0; i < members.length; i++) {
String memberName = members[i].toLowerCase();
memberName = IDNUtil.toAsciiEmail(memberName);
if (memberName.length() == 0) {
throw ServiceException.INVALID_REQUEST("invalid member email address: " + memberName, null);
}
// We do not do any further validation of the remove address for
// syntax - removes should be liberal so any bad entries added by
// some other means can be removed
//
// members[] can contain:
// - the primary address of an account or another DL
// - an alias of an account or another DL
// - junk (allAddrs will be returned as null)
AddrsOfEntry addrsOfEntry = getAllAddressesOfEntry(memberName);
List<String> allAddrs = addrsOfEntry.getAll();
if (mods.contains(memberName)) {
// already been added in mods (is the primary or alias of previous entries in members[])
} else if (existing.contains(memberName)) {
if (!allAddrs.isEmpty()) {
mods.addAll(allAddrs);
} else {
mods.add(memberName); // just get rid of it regardless what it is
}
} else {
boolean inList = false;
if (allAddrs.size() > 0) {
// go through all addresses of the entry see if any is on the DL
for (String addr : allAddrs) {
if (!inList) {
break;
}
if (existing.contains(addr)) {
mods.addAll(allAddrs);
inList = true;
}
}
}
if (!inList) {
failed.add(memberName);
}
}
// clear the DL cache on accounts/dl
String primary = addrsOfEntry.getPrimary();
if (primary != null) {
if (addrsOfEntry.isAccount()) {
Account acct = getFromCache(AccountBy.name, primary);
if (acct != null)
clearUpwardMembershipCache(acct);
} else {
removeGroupFromCache(Key.DistributionListBy.name, primary);
}
}
}
if (!failed.isEmpty()) {
StringBuilder sb = new StringBuilder();
Iterator<String> iter = failed.iterator();
while (true) {
sb.append(iter.next());
if (!iter.hasNext())
break;
sb.append(",");
}
throw AccountServiceException.NO_SUCH_MEMBER(dl.getName(), sb.toString());
}
if (mods.isEmpty()) {
throw ServiceException.INVALID_REQUEST("empty remove set", null);
}
PermissionCache.invalidateCache();
cleanGroupMembersCache(dl);
Map<String,String[]> modmap = new HashMap<String,String[]>();
modmap.put("-" + Provisioning.A_zimbraMailForwardingAddress, mods.toArray(new String[0]));
modifyAttrs(dl, modmap);
}
private void clearUpwardMembershipCache(Account acct) {
acct.setCachedData(EntryCacheDataKey.ACCOUNT_DLS, null);
acct.setCachedData(EntryCacheDataKey.ACCOUNT_DIRECT_DLS, null);
acct.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP, null);
acct.setCachedData(EntryCacheDataKey.GROUPEDENTRY_MEMBERSHIP_ADMINS_ONLY, null);
acct.setCachedData(EntryCacheDataKey.GROUPEDENTRY_DIRECT_GROUPIDS.getKeyName(), null);
}
private class AddrsOfEntry {
List<String> mAllAddrs = new ArrayList<String>(); // including primary
String mPrimary = null; // primary addr
boolean mIsAccount = false;
void setPrimary(String primary) {
mPrimary = primary;
add(primary);
}
void setIsAccount(boolean isAccount) {
mIsAccount = isAccount;
}
void add(String addr) {
mAllAddrs.add(addr);
}
void addAll(String[] addrs) {
mAllAddrs.addAll(Arrays.asList(addrs));
}
List<String> getAll() {
return mAllAddrs;
}
String getPrimary() {
return mPrimary;
}
boolean isAccount() {
return mIsAccount;
}
boolean isIn(String addr) {
return mAllAddrs.contains(addr.toLowerCase());
}
}
//
// returns the primary address and all aliases of the named account or DL
//
private AddrsOfEntry getAllAddressesOfEntry(String name) {
String primary = null;
String aliases[] = null;
AddrsOfEntry addrs = new AddrsOfEntry();
try {
// bug 56621. Do not count implicit aliases (aliases resolved by alias domain)
// when dealing with distribution list members.
Account acct = getAccountByName(name, false, false);
if (acct != null) {
addrs.setIsAccount(true);
primary = acct.getName();
aliases = acct.getMailAlias();
} else {
DistributionList dl = get(Key.DistributionListBy.name, name);
if (dl != null) {
primary = dl.getName();
aliases = dl.getAliases();
}
}
} catch (ServiceException se) {
// swallow any exception and go on
}
if (primary != null)
addrs.setPrimary(primary);
if (aliases != null)
addrs.addAll(aliases);
return addrs;
}
private List<Identity> getIdentitiesByQuery(LdapEntry entry, ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
List<Identity> result = new ArrayList<Identity>();
try {
String base = entry.getDN();
ZSearchResultEnumeration ne = helper.searchDir(base, filter,
ZSearchControls.SEARCH_CTLS_SUBTREE(), initZlc, LdapServerType.REPLICA);
while(ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapIdentity((Account)entry, sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup identity via query: "+
filter.toFilterString() + " message: "+e.getMessage(), e);
}
return result;
}
private Identity getIdentityByName(LdapEntry entry, String name, ZLdapContext zlc) throws ServiceException {
List<Identity> result = getIdentitiesByQuery(entry, filterFactory.identityByName(name), zlc);
return result.isEmpty() ? null : result.get(0);
}
private String getIdentityDn(LdapEntry entry, String name) {
return A_zimbraPrefIdentityName + "=" + LdapUtil.escapeRDNValue(name) + "," + entry.getDN();
}
private void validateIdentityAttrs(Map<String, Object> attrs) throws ServiceException {
Set<String> validAttrs = AttributeManager.getInstance().getLowerCaseAttrsInClass(AttributeClass.identity);
for (String key : attrs.keySet()) {
if (!validAttrs.contains(key.toLowerCase())) {
throw ServiceException.INVALID_REQUEST("unable to modify attr: "+key, null);
}
}
}
private static final String IDENTITY_LIST_CACHE_KEY = "LdapProvisioning.IDENTITY_CACHE";
@Override
public Identity createIdentity(Account account, String identityName,
Map<String, Object> identityAttrs)
throws ServiceException {
return createIdentity(account, identityName, identityAttrs, false);
}
@Override
public Identity restoreIdentity(Account account, String identityName,
Map<String, Object> identityAttrs)
throws ServiceException {
return createIdentity(account, identityName, identityAttrs, true);
}
private Identity createIdentity(Account account, String identityName,
Map<String, Object> identityAttrs, boolean restoring)
throws ServiceException {
removeAttrIgnoreCase("objectclass", identityAttrs);
validateIdentityAttrs(identityAttrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
if (identityName.equalsIgnoreCase(ProvisioningConstants.DEFAULT_IDENTITY_NAME))
throw AccountServiceException.IDENTITY_EXISTS(identityName);
List<Identity> existing = getAllIdentities(account);
if (existing.size() >= account.getLongAttr(A_zimbraIdentityMaxNumEntries, 20))
throw AccountServiceException.TOO_MANY_IDENTITIES();
account.setCachedData(IDENTITY_LIST_CACHE_KEY, null);
boolean checkImmutable = !restoring;
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(identityAttrs, null, callbackContext, checkImmutable);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_IDENTITY);
String dn = getIdentityDn(ldapEntry, identityName);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.setDN(dn);
entry.mapToAttrs(identityAttrs);
entry.setAttr(A_objectClass, "zimbraIdentity");
if (!entry.hasAttribute(A_zimbraPrefIdentityId)) {
String identityId = LdapUtil.generateUUID();
entry.setAttr(A_zimbraPrefIdentityId, identityId);
}
entry.setAttr(Provisioning.A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
zlc.createEntry(entry);
Identity identity = getIdentityByName(ldapEntry, identityName, zlc);
AttributeManager.getInstance().postModify(identityAttrs, identity, callbackContext);
return identity;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.IDENTITY_EXISTS(identityName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create identity " + identityName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void modifyIdentity(Account account, String identityName,
Map<String, Object> identityAttrs)
throws ServiceException {
removeAttrIgnoreCase("objectclass", identityAttrs);
validateIdentityAttrs(identityAttrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
// clear cache
account.setCachedData(IDENTITY_LIST_CACHE_KEY, null);
if (identityName.equalsIgnoreCase(ProvisioningConstants.DEFAULT_IDENTITY_NAME)) {
modifyAttrs(account, identityAttrs);
} else {
LdapIdentity identity = (LdapIdentity) getIdentityByName(ldapEntry, identityName, null);
if (identity == null)
throw AccountServiceException.NO_SUCH_IDENTITY(identityName);
String name = (String) identityAttrs.get(A_zimbraPrefIdentityName);
boolean newName = (name != null && !name.equals(identityName));
if (newName) identityAttrs.remove(A_zimbraPrefIdentityName);
modifyAttrs(identity, identityAttrs, true);
if (newName) {
// the identity cache could've been loaded again if getAllIdentities were called in pre/poseModify callback, so we clear it again
account.setCachedData(IDENTITY_LIST_CACHE_KEY, null);
renameIdentity(ldapEntry, identity, name);
}
}
}
private void renameIdentity(LdapEntry entry, LdapIdentity identity, String newIdentityName)
throws ServiceException {
if (identity.getName().equalsIgnoreCase(ProvisioningConstants.DEFAULT_IDENTITY_NAME))
throw ServiceException.INVALID_REQUEST("can't rename default identity", null);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_IDENTITY);
String newDn = getIdentityDn(entry, newIdentityName);
zlc.renameEntry(identity.getDN(), newDn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename identity: "+newIdentityName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteIdentity(Account account, String identityName) throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
if (identityName.equalsIgnoreCase(ProvisioningConstants.DEFAULT_IDENTITY_NAME))
throw ServiceException.INVALID_REQUEST("can't delete default identity", null);
account.setCachedData(IDENTITY_LIST_CACHE_KEY, null);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_IDENTITY);
Identity identity = getIdentityByName(ldapEntry, identityName, zlc);
if (identity == null)
throw AccountServiceException.NO_SUCH_IDENTITY(identityName);
String dn = getIdentityDn(ldapEntry, identityName);
zlc.deleteEntry(dn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to delete identity: "+identityName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public List<Identity> getAllIdentities(Account account) throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
@SuppressWarnings("unchecked")
List<Identity> result = (List<Identity>) account.getCachedData(IDENTITY_LIST_CACHE_KEY);
if (result != null) {
return result;
}
result = getIdentitiesByQuery(ldapEntry, filterFactory.allIdentities(), null);
for (Identity identity: result) {
// gross hack for 4.5beta. should be able to remove post 4.5
if (identity.getId() == null) {
String id = LdapUtil.generateUUID();
identity.setId(id);
Map<String, Object> newAttrs = new HashMap<String, Object>();
newAttrs.put(Provisioning.A_zimbraPrefIdentityId, id);
try {
modifyIdentity(account, identity.getName(), newAttrs);
} catch (ServiceException se) {
ZimbraLog.account.warn("error updating identity: "+account.getName()+" "+identity.getName()+" "+se.getMessage(), se);
}
}
}
result.add(getDefaultIdentity(account));
result = Collections.unmodifiableList(result);
account.setCachedData(IDENTITY_LIST_CACHE_KEY, result);
return result;
}
@Override
public Identity get(Account account, Key.IdentityBy keyType, String key)
throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
// this assumes getAllIdentities is cached and number of identities is reasaonble.
// might want a per-identity cache (i.e., use "IDENTITY_BY_ID_"+id as a key, etc)
switch(keyType) {
case id:
for (Identity identity : getAllIdentities(account))
if (identity.getId().equals(key)) return identity;
return null;
case name:
for (Identity identity : getAllIdentities(account))
if (identity.getName().equalsIgnoreCase(key)) return identity;
return null;
default:
return null;
}
}
private List<Signature> getSignaturesByQuery(Account acct, LdapEntry entry, ZLdapFilter filter,
ZLdapContext initZlc, List<Signature> result) throws ServiceException {
if (result == null) {
result = new ArrayList<Signature>();
}
try {
String base = entry.getDN();
ZSearchResultEnumeration ne = helper.searchDir(base, filter,
ZSearchControls.SEARCH_CTLS_SUBTREE(), initZlc, LdapServerType.REPLICA);
while(ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapSignature(acct, sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup signature via query: "+
filter.toFilterString() + " message: " + e.getMessage(), e);
}
return result;
}
private Signature getSignatureById(Account acct, LdapEntry entry, String id, ZLdapContext zlc)
throws ServiceException {
List<Signature> result = getSignaturesByQuery(acct, entry, filterFactory.signatureById(id), zlc, null);
return result.isEmpty() ? null : result.get(0);
}
private String getSignatureDn(LdapEntry entry, String name) {
return A_zimbraSignatureName + "=" + LdapUtil.escapeRDNValue(name) + "," + entry.getDN();
}
private void validateSignatureAttrs(Map<String, Object> attrs) throws ServiceException {
Set<String> validAttrs = AttributeManager.getInstance().getLowerCaseAttrsInClass(AttributeClass.signature);
for (String key : attrs.keySet()) {
if (!validAttrs.contains(key.toLowerCase())) {
throw ServiceException.INVALID_REQUEST("unable to modify attr: "+key, null);
}
}
}
private void setDefaultSignature(Account acct, String signatureId) throws ServiceException {
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put(Provisioning.A_zimbraPrefDefaultSignatureId, signatureId);
modifyAttrs(acct, attrs);
}
private static final String SIGNATURE_LIST_CACHE_KEY = "LdapProvisioning.SIGNATURE_CACHE";
@Override
public Signature createSignature(Account account, String signatureName, Map<String, Object> signatureAttrs) throws ServiceException {
return createSignature(account, signatureName, signatureAttrs, false);
}
@Override
public Signature restoreSignature(Account account, String signatureName, Map<String, Object> signatureAttrs) throws ServiceException {
return createSignature(account, signatureName, signatureAttrs, true);
}
private Signature createSignature(Account account, String signatureName, Map<String, Object> signatureAttrs,
boolean restoring) throws ServiceException {
signatureName = signatureName.trim();
removeAttrIgnoreCase("objectclass", signatureAttrs);
validateSignatureAttrs(signatureAttrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
/*
* check if the signature name already exists
*
* We check if the signatureName is the same as the signature on the account.
* For signatures that are in the signature LDAP entries, JNDI will throw
* NameAlreadyBoundException for duplicate names.
*
*/
Signature acctSig = LdapSignature.getAccountSignature(this, account);
if (acctSig != null && signatureName.equalsIgnoreCase(acctSig.getName()))
throw AccountServiceException.SIGNATURE_EXISTS(signatureName);
boolean setAsDefault = false;
List<Signature> existing = getAllSignatures(account);
int numSigs = existing.size();
if (numSigs >= account.getLongAttr(A_zimbraSignatureMaxNumEntries, 20))
throw AccountServiceException.TOO_MANY_SIGNATURES();
else if (numSigs == 0)
setAsDefault = true;
account.setCachedData(SIGNATURE_LIST_CACHE_KEY, null);
boolean checkImmutable = !restoring;
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
callbackContext.setData(DataKey.MAX_SIGNATURE_LEN,
account.getAttr(Provisioning.A_zimbraMailSignatureMaxLength, "1024"));
AttributeManager.getInstance().preModify(signatureAttrs, null,
callbackContext, checkImmutable);
String signatureId = (String)signatureAttrs.get(Provisioning.A_zimbraSignatureId);
if (signatureId == null) {
signatureId = LdapUtil.generateUUID();
signatureAttrs.put(Provisioning.A_zimbraSignatureId, signatureId);
}
if (acctSig == null) {
// the slot on the account is not occupied, use it
signatureAttrs.put(Provisioning.A_zimbraSignatureName, signatureName);
// pass in setAsDefault as an optimization, since we are updating the account
// entry, we can update the default attr in one LDAP write
LdapSignature.createAccountSignature(this, account, signatureAttrs, setAsDefault);
return LdapSignature.getAccountSignature(this, account);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_SIGNATURE);
String dn = getSignatureDn(ldapEntry, signatureName);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(signatureAttrs);
entry.setAttr(A_objectClass, "zimbraSignature");
entry.setAttr(Provisioning.A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setDN(dn);
zlc.createEntry(entry);
Signature signature = getSignatureById(account, ldapEntry, signatureId, zlc);
AttributeManager.getInstance().postModify(signatureAttrs, signature, callbackContext);
if (setAsDefault)
setDefaultSignature(account, signatureId);
return signature;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.SIGNATURE_EXISTS(signatureName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create signature: " + signatureName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void modifySignature(Account account, String signatureId, Map<String, Object> signatureAttrs)
throws ServiceException {
removeAttrIgnoreCase("objectclass", signatureAttrs);
validateSignatureAttrs(signatureAttrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
String newName = (String) signatureAttrs.get(A_zimbraSignatureName);
if (newName != null) {
newName = newName.trim();
// do not allow name to be wiped
if (newName.length()==0)
throw ServiceException.INVALID_REQUEST("empty signature name is not allowed", null);
// check for duplicate names
List<Signature> sigs = getAllSignatures(account);
for (Signature sig : sigs) {
if (sig.getName().equalsIgnoreCase(newName) && !sig.getId().equals(signatureId))
throw AccountServiceException.SIGNATURE_EXISTS(newName);
}
}
// clear cache
account.setCachedData(SIGNATURE_LIST_CACHE_KEY, null);
if (LdapSignature.isAccountSignature(account, signatureId)) {
LdapSignature.modifyAccountSignature(this, account, signatureAttrs);
} else {
LdapSignature signature = (LdapSignature) getSignatureById(account, ldapEntry, signatureId, null);
if (signature == null)
throw AccountServiceException.NO_SUCH_SIGNATURE(signatureId);
boolean nameChanged = (newName != null && !newName.equals(signature.getName()));
if (nameChanged)
signatureAttrs.remove(A_zimbraSignatureName);
modifyAttrs(signature, signatureAttrs, true);
if (nameChanged) {
// the signature cache could've been loaded again if getAllSignatures
// were called in pre/poseModify callback, so we clear it again
account.setCachedData(SIGNATURE_LIST_CACHE_KEY, null);
renameSignature(ldapEntry, signature, newName);
}
}
}
private void renameSignature(LdapEntry entry, LdapSignature signature, String newSignatureName)
throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_SIGNATURE);
String newDn = getSignatureDn(entry, newSignatureName);
zlc.renameEntry(signature.getDN(), newDn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename signature: "+newSignatureName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteSignature(Account account, String signatureId) throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
account.setCachedData(SIGNATURE_LIST_CACHE_KEY, null);
if (LdapSignature.isAccountSignature(account, signatureId)) {
LdapSignature.deleteAccountSignature(this, account);
} else {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_SIGNATURE);
Signature signature = getSignatureById(account, ldapEntry, signatureId, zlc);
if (signature == null)
throw AccountServiceException.NO_SUCH_SIGNATURE(signatureId);
String dn = getSignatureDn(ldapEntry, signature.getName());
zlc.deleteEntry(dn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to delete signarure: " + signatureId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
if (signatureId.equals(account.getPrefDefaultSignatureId())) {
account.unsetPrefDefaultSignatureId();
}
}
@Override
public List<Signature> getAllSignatures(Account account) throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
@SuppressWarnings("unchecked")
List<Signature> result = (List<Signature>) account.getCachedData(SIGNATURE_LIST_CACHE_KEY);
if (result != null) {
return result;
}
result = new ArrayList<Signature>();
Signature acctSig = LdapSignature.getAccountSignature(this, account);
if (acctSig != null)
result.add(acctSig);
result = getSignaturesByQuery(account, ldapEntry, filterFactory.allSignatures(), null, result);
result = Collections.unmodifiableList(result);
account.setCachedData(SIGNATURE_LIST_CACHE_KEY, result);
return result;
}
@Override
public Signature get(Account account, Key.SignatureBy keyType, String key)
throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
// this assumes getAllSignatures is cached and number of signatures is reasaonble.
// might want a per-signature cache (i.e., use "SIGNATURE_BY_ID_"+id as a key, etc)
switch(keyType) {
case id:
for (Signature signature : getAllSignatures(account))
if (signature.getId().equals(key)) return signature;
return null;
case name:
for (Signature signature : getAllSignatures(account))
if (signature.getName().equalsIgnoreCase(key)) return signature;
return null;
default:
return null;
}
}
private static final String DATA_SOURCE_LIST_CACHE_KEY = "LdapProvisioning.DATA_SOURCE_CACHE";
private List<DataSource> getDataSourcesByQuery(LdapEntry entry, ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
List<DataSource> result = new ArrayList<DataSource>();
try {
String base = entry.getDN();
ZSearchResultEnumeration ne = helper.searchDir(base, filter,
ZSearchControls.SEARCH_CTLS_SUBTREE(), initZlc, LdapServerType.REPLICA);
while(ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
result.add(new LdapDataSource((Account)entry, sr.getDN(), sr.getAttributes(), this));
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup data source via query: "+
filter.toFilterString() + " message: " + e.getMessage(), e);
}
return result;
}
private DataSource getDataSourceById(LdapEntry entry, String id, ZLdapContext zlc)
throws ServiceException {
List<DataSource> result = getDataSourcesByQuery(entry, filterFactory.dataSourceById(id), zlc);
return result.isEmpty() ? null : result.get(0);
}
private String getDataSourceDn(LdapEntry entry, String name) {
return A_zimbraDataSourceName + "=" + LdapUtil.escapeRDNValue(name) + "," + entry.getDN();
}
protected ReplaceAddressResult replaceMailAddresses(Entry entry, String attrName,
String oldAddr, String newAddr)
throws ServiceException {
String oldDomain = EmailUtil.getValidDomainPart(oldAddr);
String newDomain = EmailUtil.getValidDomainPart(newAddr);
String oldAddrs[] = entry.getMultiAttr(attrName);
String newAddrs[] = new String[0];
for (int i = 0; i < oldAddrs.length; i++) {
String oldMail = oldAddrs[i];
if (oldMail.equals(oldAddr)) {
// exact match, replace the entire old addr with new addr
newAddrs = addMultiValue(newAddrs, newAddr);
} else {
String[] oldParts = EmailUtil.getLocalPartAndDomain(oldMail);
// sanity check, or should we ignore and continue?
if (oldParts == null)
throw ServiceException.FAILURE("bad value for " + attrName + " " + oldMail, null);
String oldL = oldParts[0];
String oldD = oldParts[1];
if (oldD.equals(oldDomain)) {
// old domain is the same as the domain being renamed,
// - keep the local part
// - replace the domain with new domain
String newMail = oldL + "@" + newDomain;
newAddrs = addMultiValue(newAddrs, newMail);
} else {
// address is not in the domain being renamed, keep as is
newAddrs = addMultiValue(newAddrs, oldMail);
}
}
}
// returns a pair of parallel arrays of old and new addrs
return new ReplaceAddressResult(oldAddrs, newAddrs);
}
// MOVE OVER ALL aliases. doesn't throw an exception, just logs
// There could be a race condition that the alias might get taken
// in the new domain post the check. Anyone who calls this API must
// pay attention to the warning message
private void moveAliases(ZLdapContext zlc, ReplaceAddressResult addrs,
String newDomain, String primaryUid,
String targetOldDn, String targetNewDn,
String targetOldDomain, String targetNewDomain)
throws ServiceException {
for (int i=0; i < addrs.newAddrs().length; i++) {
String oldAddr = addrs.oldAddrs()[i];
String newAddr = addrs.newAddrs()[i];
String aliasNewDomain = EmailUtil.getValidDomainPart(newAddr);
if (aliasNewDomain.equals(newDomain)) {
String[] oldParts = EmailUtil.getLocalPartAndDomain(oldAddr);
String oldAliasDN = mDIT.aliasDN(targetOldDn, targetOldDomain, oldParts[0], oldParts[1]);
String newAliasDN = mDIT.aliasDNRename(targetNewDn, targetNewDomain, newAddr);
if (oldAliasDN.equals(newAliasDN))
continue;
// skip the extra alias that is the same as the primary
String newAliasParts[] = EmailUtil.getLocalPartAndDomain(newAddr);
String newAliasLocal = newAliasParts[0];
if (!(primaryUid != null && newAliasLocal.equals(primaryUid))) {
try {
zlc.renameEntry(oldAliasDN, newAliasDN);
} catch (LdapEntryAlreadyExistException nabe) {
ZimbraLog.account.warn("unable to move alias from " + oldAliasDN + " to " + newAliasDN, nabe);
} catch (ServiceException ne) {
throw ServiceException.FAILURE("unable to move aliases", null);
} finally {
}
}
}
}
}
@Override
public DataSource createDataSource(Account account, DataSourceType dsType,
String dsName, Map<String, Object> dataSourceAttrs)
throws ServiceException {
return createDataSource(account, dsType, dsName, dataSourceAttrs, false);
}
@Override
public DataSource createDataSource(Account account, DataSourceType type,
String dataSourceName, Map<String, Object> attrs,
boolean passwdAlreadyEncrypted)
throws ServiceException {
return createDataSource(account, type, dataSourceName, attrs, passwdAlreadyEncrypted, false);
}
@Override
public DataSource restoreDataSource(Account account, DataSourceType dsType,
String dsName, Map<String, Object> dataSourceAttrs)
throws ServiceException {
return createDataSource(account, dsType, dsName, dataSourceAttrs, true, true);
}
private DataSource createDataSource(Account account, DataSourceType dsType,
String dsName, Map<String, Object> dataSourceAttrs,
boolean passwdAlreadyEncrypted, boolean restoring)
throws ServiceException {
removeAttrIgnoreCase("objectclass", dataSourceAttrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
List<DataSource> existing = getAllDataSources(account);
if (existing.size() >= account.getLongAttr(A_zimbraDataSourceMaxNumEntries, 20))
throw AccountServiceException.TOO_MANY_DATA_SOURCES();
dataSourceAttrs.put(A_zimbraDataSourceName, dsName); // must be the same
dataSourceAttrs.put(Provisioning.A_zimbraDataSourceType, dsType.toString());
account.setCachedData(DATA_SOURCE_LIST_CACHE_KEY, null);
boolean checkImmutable = !restoring;
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(dataSourceAttrs, null, callbackContext, checkImmutable);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_DATASOURCE);
String dn = getDataSourceDn(ldapEntry, dsName);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.setDN(dn);
entry.mapToAttrs(dataSourceAttrs);
entry.setAttr(A_objectClass, "zimbraDataSource");
String extraOc = LdapDataSource.getObjectClass(dsType);
if (extraOc != null) {
entry.addAttr(A_objectClass, Sets.newHashSet(extraOc));
}
String dsId = entry.getAttrString(A_zimbraDataSourceId);
if (dsId == null) {
dsId = LdapUtil.generateUUID();
entry.setAttr(A_zimbraDataSourceId, dsId);
}
String password = entry.getAttrString(A_zimbraDataSourcePassword);
if (password != null) {
String encrypted = passwdAlreadyEncrypted ? password : DataSource.encryptData(dsId, password);
entry.setAttr(A_zimbraDataSourcePassword, encrypted);
}
entry.setAttr(Provisioning.A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
zlc.createEntry(entry);
DataSource ds = getDataSourceById(ldapEntry, dsId, zlc);
AttributeManager.getInstance().postModify(dataSourceAttrs, ds, callbackContext);
return ds;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DATA_SOURCE_EXISTS(dsName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create data source: " + dsName, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteDataSource(Account account, String dataSourceId) throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
account.setCachedData(DATA_SOURCE_LIST_CACHE_KEY, null);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_DATASOURCE);
DataSource dataSource = getDataSourceById(ldapEntry, dataSourceId, zlc);
if (dataSource == null)
throw AccountServiceException.NO_SUCH_DATA_SOURCE(dataSourceId);
String dn = getDataSourceDn(ldapEntry, dataSource.getName());
zlc.deleteEntry(dn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to delete data source: "+dataSourceId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public List<DataSource> getAllDataSources(Account account) throws ServiceException {
@SuppressWarnings("unchecked")
List<DataSource> result = (List<DataSource>) account.getCachedData(DATA_SOURCE_LIST_CACHE_KEY);
if (result != null) {
return result;
}
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
result = getDataSourcesByQuery(ldapEntry, filterFactory.allDataSources(), null);
result = Collections.unmodifiableList(result);
account.setCachedData(DATA_SOURCE_LIST_CACHE_KEY, result);
return result;
}
public void removeAttrIgnoreCase(String attr, Map<String, Object> attrs) {
for (String key : attrs.keySet()) {
if (key.equalsIgnoreCase(attr)) {
attrs.remove(key);
return;
}
}
}
@Override
public void modifyDataSource(Account account, String dataSourceId, Map<String, Object> attrs)
throws ServiceException {
removeAttrIgnoreCase("objectclass", attrs);
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
LdapDataSource ds = (LdapDataSource) getDataSourceById(ldapEntry, dataSourceId, null);
if (ds == null)
throw AccountServiceException.NO_SUCH_DATA_SOURCE(dataSourceId);
account.setCachedData(DATA_SOURCE_LIST_CACHE_KEY, null);
attrs.remove(A_zimbraDataSourceId);
String name = (String) attrs.get(A_zimbraDataSourceName);
boolean newName = (name != null && !name.equals(ds.getName()));
if (newName) attrs.remove(A_zimbraDataSourceName);
String password = (String) attrs.get(A_zimbraDataSourcePassword);
if (password != null) {
attrs.put(A_zimbraDataSourcePassword, DataSource.encryptData(ds.getId(), password));
}
modifyAttrs(ds, attrs, true);
if (newName) {
// the datasoruce cache could've been loaded again if getAllDataSources were called in pre/poseModify callback, so we clear it again
account.setCachedData(DATA_SOURCE_LIST_CACHE_KEY, null);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_DATASOURCE);
String newDn = getDataSourceDn(ldapEntry, name);
zlc.renameEntry(ds.getDN(), newDn);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename datasource: "+name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
}
@Override
public DataSource get(Account account, Key.DataSourceBy keyType, String key)
throws ServiceException {
LdapEntry ldapEntry = (LdapEntry) (account instanceof LdapEntry ? account : getAccountById(account.getId()));
if (ldapEntry == null)
throw AccountServiceException.NO_SUCH_ACCOUNT(account.getName());
// this assumes getAllDataSources is cached and number of data sources is reasaonble.
// might want a per-data-source cache (i.e., use "DATA_SOURCE_BY_ID_"+id as a key, etc)
switch(keyType) {
case id:
for (DataSource source : getAllDataSources(account))
if (source.getId().equals(key))
return source;
return null;
//return getDataSourceById(ldapEntry, key, null);
case name:
for (DataSource source : getAllDataSources(account))
if (source.getName().equalsIgnoreCase(key))
return source;
return null;
//return getDataSourceByName(ldapEntry, key, null);
default:
return null;
}
}
private XMPPComponent getXMPPComponentByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.xmppcomponentBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapXMPPComponent(sr.getDN(), sr.getAttributes(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getXMPPComponentByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup XMPP component via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private XMPPComponent getXMPPComponentByName(String name, boolean nocache)
throws ServiceException {
if (!nocache) {
XMPPComponent x = xmppComponentCache.getByName(name);
if (x != null)
return x;
}
try {
String dn = mDIT.xmppcomponentNameToDN(name);
ZAttributes attrs = helper.getAttributes(LdapUsage.GET_XMPPCOMPONENT, dn);
XMPPComponent x = new LdapXMPPComponent(dn, attrs, this);
xmppComponentCache.put(x);
return x;
} catch (LdapEntryNotFoundException e) {
return null;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup xmpp component by name: "+name+" message: "+e.getMessage(), e);
}
}
private XMPPComponent getXMPPComponentById(String zimbraId, ZLdapContext zlc, boolean nocache)
throws ServiceException {
if (zimbraId == null)
return null;
XMPPComponent x = null;
if (!nocache)
x = xmppComponentCache.getById(zimbraId);
if (x == null) {
x = getXMPPComponentByQuery(filterFactory.xmppComponentById(zimbraId), zlc);
xmppComponentCache.put(x);
}
return x;
}
@Override
public List<XMPPComponent> getAllXMPPComponents() throws ServiceException {
List<XMPPComponent> result = new ArrayList<XMPPComponent>();
try {
String base = mDIT.xmppcomponentBaseDN();
ZLdapFilter filter = filterFactory.allXMPPComponents();
ZSearchResultEnumeration ne = helper.searchDir(base, filter, ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
LdapXMPPComponent x = new LdapXMPPComponent(sr.getDN(), sr.getAttributes(), this);
result.add(x);
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all XMPPComponents", e);
}
if (result.size() > 0) {
xmppComponentCache.put(result, true);
}
Collections.sort(result);
return result;
}
@Override
public XMPPComponent createXMPPComponent(String name, Domain domain, Server server,
Map<String, Object> inAttrs)
throws ServiceException {
name = name.toLowerCase().trim();
// sanity checking
removeAttrIgnoreCase("objectclass", inAttrs);
removeAttrIgnoreCase(A_zimbraDomainId, inAttrs);
removeAttrIgnoreCase(A_zimbraServerId, inAttrs);
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(inAttrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_XMPPCOMPONENT);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(inAttrs);
entry.setAttr(A_objectClass, "zimbraXMPPComponent");
String compId = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, compId);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_cn, name);
String dn = mDIT.xmppcomponentNameToDN(name);
entry.setDN(dn);
entry.setAttr(A_zimbraDomainId, domain.getId());
entry.setAttr(A_zimbraServerId, server.getId());
zlc.createEntry(entry);
XMPPComponent comp = getXMPPComponentById(compId, zlc, true);
AttributeManager.getInstance().postModify(inAttrs, comp, callbackContext);
return comp;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.IM_COMPONENT_EXISTS(name);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public XMPPComponent get(Key.XMPPComponentBy keyType, String key) throws ServiceException {
switch(keyType) {
case name:
return getXMPPComponentByName(key, false);
case id:
return getXMPPComponentById(key, null, false);
case serviceHostname:
throw new UnsupportedOperationException("Writeme!");
default:
}
return null;
}
@Override
public void deleteXMPPComponent(XMPPComponent comp) throws ServiceException {
String zimbraId = comp.getId();
ZLdapContext zlc = null;
LdapXMPPComponent l = (LdapXMPPComponent)get(Key.XMPPComponentBy.id, zimbraId);
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_XMPPCOMPONENT);
zlc.deleteEntry(l.getDN());
xmppComponentCache.remove(l);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge XMPPComponent : "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
// Only called from renameDomain for now
void renameXMPPComponent(String zimbraId, String newName) throws ServiceException {
LdapXMPPComponent comp = (LdapXMPPComponent)get(Key.XMPPComponentBy.id, zimbraId);
if (comp == null)
throw AccountServiceException.NO_SUCH_XMPP_COMPONENT(zimbraId);
newName = newName.toLowerCase().trim();
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_XMPPCOMPONENT);
String newDn = mDIT.xmppcomponentNameToDN(newName);
zlc.renameEntry(comp.getDN(), newDn);
// remove old comp from cache
xmppComponentCache.remove(comp);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.IM_COMPONENT_EXISTS(newName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename XMPPComponent: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
//
// rights
//
@Override
/*
* from zmprov -l, we don't expand all attrs, expandAllAttrs is ignored
*/
public Right getRight(String rightName, boolean expandAllAttrs) throws ServiceException {
if (expandAllAttrs)
throw ServiceException.FAILURE("expandAllAttrs is not supported", null);
return RightCommand.getRight(rightName);
}
@Override
/*
* from zmprov -l, we don't expand all attrs, expandAllAttrs is ignored
*/
public List<Right> getAllRights(String targetType, boolean expandAllAttrs, String rightClass)
throws ServiceException {
if (expandAllAttrs)
throw ServiceException.FAILURE("expandAllAttrs == TRUE is not supported", null);
return RightCommand.getAllRights(targetType, rightClass);
}
@Override
public boolean checkRight(String targetType, TargetBy targetBy, String target,
Key.GranteeBy granteeBy, String grantee,
String right, Map<String, Object> attrs,
AccessManager.ViaGrant via) throws ServiceException {
GuestAccount guest = null;
try {
GranteeType.lookupGrantee(this, GranteeType.GT_USER, granteeBy, grantee);
} catch (ServiceException e) {
guest = new GuestAccount(grantee, null);
}
return RightCommand.checkRight(this,
targetType, targetBy, target,
granteeBy, grantee, guest,
right, attrs, via);
}
@Override
public RightCommand.AllEffectiveRights getAllEffectiveRights(
String granteeType, Key.GranteeBy granteeBy, String grantee,
boolean expandSetAttrs, boolean expandGetAttrs) throws ServiceException {
return RightCommand.getAllEffectiveRights(this,
granteeType, granteeBy, grantee,
expandSetAttrs, expandGetAttrs);
}
@Override
public RightCommand.EffectiveRights getEffectiveRights(
String targetType, TargetBy targetBy, String target,
Key.GranteeBy granteeBy, String grantee,
boolean expandSetAttrs, boolean expandGetAttrs) throws ServiceException {
return RightCommand.getEffectiveRights(this,
targetType, targetBy, target,
granteeBy, grantee,
expandSetAttrs, expandGetAttrs);
}
@Override
public EffectiveRights getCreateObjectAttrs(String targetType,
Key.DomainBy domainBy, String domainStr,
Key.CosBy cosBy, String cosStr,
Key.GranteeBy granteeBy, String grantee)
throws ServiceException {
return RightCommand.getCreateObjectAttrs(this,
targetType,
domainBy, domainStr,
cosBy, cosStr,
granteeBy, grantee);
}
@Override
public RightCommand.Grants getGrants(String targetType, TargetBy targetBy, String target,
String granteeType, Key.GranteeBy granteeBy, String grantee,
boolean granteeIncludeGroupsGranteeBelongs)
throws ServiceException {
return RightCommand.getGrants(this, targetType, targetBy, target,
granteeType, granteeBy, grantee, granteeIncludeGroupsGranteeBelongs);
}
@Override
public void grantRight(String targetType, TargetBy targetBy, String target,
String granteeType, Key.GranteeBy granteeBy, String grantee, String secret,
String right, RightModifier rightModifier)
throws ServiceException {
RightCommand.grantRight(this,
null,
targetType, targetBy, target,
granteeType, granteeBy, grantee, secret,
right, rightModifier);
}
@Override
public void revokeRight(String targetType, TargetBy targetBy, String target,
String granteeType, Key.GranteeBy granteeBy, String grantee,
String right, RightModifier rightModifier)
throws ServiceException {
RightCommand.revokeRight(this,
null,
targetType, targetBy, target,
granteeType, granteeBy, grantee,
right, rightModifier);
}
@Override
public void flushCache(CacheEntryType type, CacheEntry[] entries) throws ServiceException {
switch (type) {
case all:
if (entries != null) {
throw ServiceException.INVALID_REQUEST("cannot specify entry for flushing all", null);
}
ZimbraLog.account.info("Flushing all LDAP entry caches");
flushCache(CacheEntryType.account, null);
flushCache(CacheEntryType.group, null);
flushCache(CacheEntryType.config, null);
flushCache(CacheEntryType.globalgrant, null);
flushCache(CacheEntryType.cos, null);
flushCache(CacheEntryType.domain, null);
flushCache(CacheEntryType.mime, null);
flushCache(CacheEntryType.server, null);
flushCache(CacheEntryType.zimlet, null);
break;
case account:
if (entries != null) {
for (CacheEntry entry : entries) {
AccountBy accountBy = (entry.mEntryBy==Key.CacheEntryBy.id)? AccountBy.id : AccountBy.name;
Account account = getFromCache(accountBy, entry.mEntryIdentity);
/*
* We now call removeFromCache instead of reload for flushing an account
* from cache. This change was originally for bug 25028, but that would still
* need an extrat step to flush cache after the account's zimbraCOSId changed.
* (if we call reload insteasd of removeFromCache, flush cache of the account would
* not clear the mDefaults for inherited attrs, that was the bug.)
* Bug 25028 is now taken care of by the callback. We still call removeFromCache
* for flushing account cache, because that does a cleaner flush.
*
* Note, we only call removeFromCache for account.
* We should *NOT* do removeFromCache when flushing global config and cos caches.
*
* Because the "mDefaults" Map(contains a ref to the old instance of COS.mAccountDefaults for
* all the accountInherited COS attrs) stored in all the cached accounts. Same for the
* inherited attrs of server/domain from global config. If we do removeFromCache for flushing
* cos/global config, then after FlushCache(cos) if you do a ga on a cached account, it still
* shows the old COS value for values that are inherited from COS. Although, for newly loaded
* accounts or when a cached account is going thru auth(that'll trigger a reload) they will get
* the new COS values(refreshed as a result of FlushCache(cos)).
*/
if (account != null) {
removeFromCache(account);
}
}
} else {
accountCache.clear();
}
return;
case group:
if (entries != null) {
for (CacheEntry entry : entries) {
Key.DistributionListBy dlBy = (entry.mEntryBy==Key.CacheEntryBy.id)?
Key.DistributionListBy.id : Key.DistributionListBy.name;
removeGroupFromCache(dlBy, entry.mEntryIdentity);
}
} else {
groupCache.clear();
}
return;
case config:
if (entries != null) {
throw ServiceException.INVALID_REQUEST("cannot specify entry for flushing global config", null);
}
Config config = getConfig();
reload(config, false);
return;
case globalgrant:
if (entries != null) {
throw ServiceException.INVALID_REQUEST("cannot specify entry for flushing global grant", null);
}
GlobalGrant globalGrant = getGlobalGrant();
reload(globalGrant, false);
return;
case cos:
if (entries != null) {
for (CacheEntry entry : entries) {
Key.CosBy cosBy = (entry.mEntryBy==Key.CacheEntryBy.id)? Key.CosBy.id : Key.CosBy.name;
Cos cos = getFromCache(cosBy, entry.mEntryIdentity);
if (cos != null)
reload(cos, false);
}
} else
cosCache.clear();
return;
case domain:
if (entries != null) {
for (CacheEntry entry : entries) {
Key.DomainBy domainBy = (entry.mEntryBy==Key.CacheEntryBy.id)? Key.DomainBy.id : Key.DomainBy.name;
Domain domain = getFromCache(domainBy, entry.mEntryIdentity, GetFromDomainCacheOption.BOTH);
if (domain != null) {
if (domain instanceof DomainCache.NonExistingDomain)
domainCache.removeFromNegativeCache(domainBy, entry.mEntryIdentity);
else
reload(domain, false);
}
}
} else
domainCache.clear();
return;
case mime:
mimeTypeCache.flushCache(this);
return;
case server:
if (entries != null) {
for (CacheEntry entry : entries) {
Key.ServerBy serverBy = (entry.mEntryBy==Key.CacheEntryBy.id)? Key.ServerBy.id : Key.ServerBy.name;
Server server = get(serverBy, entry.mEntryIdentity);
if (server != null)
reload(server, false);
}
} else
serverCache.clear();
return;
case zimlet:
if (entries != null) {
for (CacheEntry entry : entries) {
Key.ZimletBy zimletBy = (entry.mEntryBy==Key.CacheEntryBy.id)? Key.ZimletBy.id : Key.ZimletBy.name;
Zimlet zimlet = getFromCache(zimletBy, entry.mEntryIdentity);
if (zimlet != null)
reload(zimlet, false);
}
} else
zimletCache.clear();
return;
default:
throw ServiceException.INVALID_REQUEST("invalid cache type "+type, null);
}
}
@Override // LdapProv
public void removeFromCache(Entry entry) {
if (entry instanceof Account) {
accountCache.remove((Account)entry);
} else if (entry instanceof Group) {
groupCache.remove((Group)entry);
} else {
throw new UnsupportedOperationException();
}
}
private static class CountAccountVisitor implements NamedEntry.Visitor {
private static class Result {
Result(String name) {
mName = name;
mCount= 0;
}
String mName;
long mCount;
}
Provisioning mProv;
Map<String, Result> mResult = new HashMap<String, Result>();
CountAccountVisitor(Provisioning prov) {
mProv = prov;
}
@Override
public void visit(NamedEntry entry) throws ServiceException {
if (!(entry instanceof Account))
return;
if (entry instanceof CalendarResource)
return;
Account acct = (Account)entry;
if (acct.getBooleanAttr(Provisioning.A_zimbraIsSystemResource, false))
return;
Cos cos = mProv.getCOS(acct);
Result r = mResult.get(cos.getId());
if (r == null) {
r = new Result(cos.getName());
mResult.put(cos.getId(), r);
}
r.mCount++;
}
CountAccountResult getResult() {
CountAccountResult result = new CountAccountResult();
for (Map.Entry<String, Result> r : mResult.entrySet()) {
result.addCountAccountByCosResult(r.getKey(), r.getValue().mName, r.getValue().mCount);
}
return result;
}
}
@Override
public CountAccountResult countAccount(Domain domain) throws ServiceException {
CountAccountVisitor visitor = new CountAccountVisitor(this);
SearchAccountsOptions option = new SearchAccountsOptions(domain,
new String[]{Provisioning.A_zimbraCOSId,
Provisioning.A_zimbraIsSystemResource});
option.setIncludeType(IncludeType.ACCOUNTS_ONLY);
option.setFilter(mDIT.filterAccountsOnlyByDomain(domain));
searchDirectoryInternal(option, visitor);
return visitor.getResult();
}
@Override
public long countObjects(CountObjectsType type, Domain domain, UCService ucService)
throws ServiceException {
if (domain != null && !type.allowsDomain()) {
throw ServiceException.INVALID_REQUEST(
"domain cannot be specified for counting type: " + type.toString(), null);
}
if (ucService != null && !type.allowsUCService()) {
throw ServiceException.INVALID_REQUEST(
"UCService cannot be specified for counting type: " + type.toString(), null);
}
ZLdapFilter filter;
// setup types for finding bases
Set<ObjectType> types = Sets.newHashSet();
switch (type) {
case userAccount:
types.add(ObjectType.accounts);
filter = filterFactory.allNonSystemAccounts();
break;
case internalUserAccount:
types.add(ObjectType.accounts);
filter = filterFactory.allNonSystemInternalAccounts();
break;
case internalArchivingAccount:
types.add(ObjectType.accounts);
filter = filterFactory.allNonSystemArchivingAccounts();
break;
case account:
types.add(ObjectType.accounts);
types.add(ObjectType.resources);
filter = filterFactory.allAccounts();
break;
case alias:
types.add(ObjectType.aliases);
filter = filterFactory.allAliases();
break;
case dl:
types.add(ObjectType.distributionlists);
types.add(ObjectType.dynamicgroups);
filter = mDIT.filterGroupsByDomain(domain);
if (domain != null && !InMemoryLdapServer.isOn()) {
ZLdapFilter dnSubtreeMatchFilter = ((LdapDomain) domain).getDnSubtreeMatchFilter();
filter = filterFactory.andWith(filter, dnSubtreeMatchFilter);
}
break;
case calresource:
types.add(ObjectType.resources);
filter = filterFactory.allCalendarResources();
break;
case domain:
types.add(ObjectType.domains);
filter = filterFactory.allDomains();
break;
case cos:
types.add(ObjectType.coses);
filter = filterFactory.allCoses();
break;
case server:
types.add(ObjectType.servers);
filter = filterFactory.allServers();
break;
case accountOnUCService:
if (ucService == null) {
throw ServiceException.INVALID_REQUEST(
"UCService is required for counting type: " + type.toString(), null);
}
types.add(ObjectType.accounts);
types.add(ObjectType.resources);
filter = filterFactory.accountsOnUCService(ucService.getId());
break;
case cosOnUCService:
if (ucService == null) {
throw ServiceException.INVALID_REQUEST(
"UCService is required for counting type: " + type.toString(), null);
}
types.add(ObjectType.coses);
filter = filterFactory.cosesOnUCService(ucService.getId());
break;
case domainOnUCService:
if (ucService == null) {
throw ServiceException.INVALID_REQUEST(
"UCService is required for counting type: " + type.toString(), null);
}
types.add(ObjectType.domains);
filter = filterFactory.domainsOnUCService(ucService.getId());
break;
default:
throw ServiceException.INVALID_REQUEST("unsupported counting type:" + type.toString(), null);
}
String[] bases = getSearchBases(domain, types);
long num = 0;
for (String base : bases) {
num += countObjects(base, filter);
}
return num;
}
private long countObjects(String base, ZLdapFilter filter)
throws ServiceException {
ZSearchControls searchControls = ZSearchControls.createSearchControls(
ZSearchScope.SEARCH_SCOPE_SUBTREE, ZSearchControls.SIZE_UNLIMITED, null);
return helper.countEntries(base, filter, searchControls);
}
@Override
public Map<String, String> getNamesForIds(Set<String> ids, EntryType type)
throws ServiceException {
final Map<String, String> result = new HashMap<String, String>();
Set<String> unresolvedIds;
NamedEntry entry;
final String nameAttr;
final EntryType entryType = type;
String base;
String objectClass;
switch (entryType) {
case account:
unresolvedIds = new HashSet<String>();
for (String id : ids) {
entry = accountCache.getById(id);
if (entry != null)
result.put(id, entry.getName());
else
unresolvedIds.add(id);
}
nameAttr = Provisioning.A_zimbraMailDeliveryAddress;
base = mDIT.mailBranchBaseDN();
objectClass = AttributeClass.OC_zimbraAccount;
break;
case group:
unresolvedIds = ids;
nameAttr = Provisioning.A_uid; // see dnToEmail
base = mDIT.mailBranchBaseDN();
objectClass = AttributeClass.OC_zimbraDistributionList;
break;
case cos:
unresolvedIds = new HashSet<String>();
for (String id : ids) {
entry = cosCache.getById(id);
if (entry != null)
result.put(id, entry.getName());
else
unresolvedIds.add(id);
}
nameAttr = Provisioning.A_cn;
base = mDIT.cosBaseDN();
objectClass = AttributeClass.OC_zimbraCOS;
break;
case domain:
unresolvedIds = new HashSet<String>();
for (String id : ids) {
entry = getFromCache(Key.DomainBy.id, id, GetFromDomainCacheOption.POSITIVE);
if (entry != null)
result.put(id, entry.getName());
else
unresolvedIds.add(id);
}
nameAttr = Provisioning.A_zimbraDomainName;
base = mDIT.domainBaseDN();
objectClass = AttributeClass.OC_zimbraDomain;
break;
default:
throw ServiceException.FAILURE("unsupported entry type for getNamesForIds" + type.name(), null);
}
// we are done if all ids can be resolved in our cache
if (unresolvedIds.size() == 0)
return result;
SearchLdapVisitor visitor = new SearchLdapVisitor() {
@Override
public void visit(String dn, Map<String, Object> attrs, IAttributes ldapAttrs) {
String id = (String)attrs.get(Provisioning.A_zimbraId);
String name = null;
try {
switch (entryType) {
case account:
name = ldapAttrs.getAttrString(Provisioning.A_zimbraMailDeliveryAddress);
if (name == null)
name = mDIT.dnToEmail(dn, ldapAttrs);
break;
case group:
name = mDIT.dnToEmail(dn, ldapAttrs);
break;
case cos:
name = ldapAttrs.getAttrString(Provisioning.A_cn);
break;
case domain:
name = ldapAttrs.getAttrString(Provisioning.A_zimbraDomainName);
break;
}
} catch (ServiceException e) {
name = null;
}
if (name != null)
result.put(id, name);
}
};
String returnAttrs[] = new String[] {Provisioning.A_zimbraId, nameAttr};
searchNamesForIds(unresolvedIds, base, objectClass, returnAttrs, visitor);
return result;
}
public void searchNamesForIds(Set<String> unresolvedIds, String base,
String objectClass, String returnAttrs[],
SearchLdapOptions.SearchLdapVisitor visitor)
throws ServiceException {
final int batchSize = 10; // num ids per search
final String queryStart = "(&(objectClass=" + objectClass + ")(|";
final String queryEnd = "))";
StringBuilder query = new StringBuilder();
query.append(queryStart);
int i = 0;
for (String id : unresolvedIds) {
query.append("(" + Provisioning.A_zimbraId + "=" + id + ")");
if ((++i) % batchSize == 0) {
query.append(queryEnd);
searchLdapOnReplica(base, query.toString(), returnAttrs, visitor);
query.setLength(0);
query.append(queryStart);
}
}
// one more search if there are remainding
if (query.length() != queryStart.length()) {
query.append(queryEnd);
searchLdapOnReplica(base, query.toString(), returnAttrs, visitor);
}
}
@Override
public Map<String, Map<String, Object>> getDomainSMIMEConfig(Domain domain, String configName)
throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(domain);
return smime.get(configName);
}
@Override
public void modifyDomainSMIMEConfig(Domain domain, String configName, Map<String, Object> attrs)
throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(domain);
smime.modify(configName, attrs);
}
@Override
public void removeDomainSMIMEConfig(Domain domain, String configName) throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(domain);
smime.remove(configName);
}
@Override
public Map<String, Map<String, Object>> getConfigSMIMEConfig(String configName)
throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(getConfig());
return smime.get(configName);
}
@Override
public void modifyConfigSMIMEConfig(String configName, Map<String, Object> attrs)
throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(getConfig());
smime.modify(configName, attrs);
}
@Override
public void removeConfigSMIMEConfig(String configName) throws ServiceException {
LdapSMIMEConfig smime = LdapSMIMEConfig.getInstance(getConfig());
smime.remove(configName);
}
@Override
public void searchLdapOnMaster(String base, String filter,
String[] returnAttrs, SearchLdapVisitor visitor)
throws ServiceException {
searchZimbraLdap(base, filter, returnAttrs, true, visitor);
}
@Override
public void searchLdapOnReplica(String base, String filter,
String[] returnAttrs, SearchLdapVisitor visitor)
throws ServiceException {
searchZimbraLdap(base, filter, returnAttrs, false, visitor);
}
@Override
@TODO // modify SearchLdapOptions to take a ZLdapFilter
public void searchLdapOnMaster(String base, ZLdapFilter filter,
String[] returnAttrs, SearchLdapVisitor visitor)
throws ServiceException {
searchLdapOnMaster(base, filter.toFilterString(), returnAttrs, visitor);
}
@Override
@TODO // modify SearchLdapOptions to take a ZLdapFilter
public void searchLdapOnReplica(String base, ZLdapFilter filter,
String[] returnAttrs, SearchLdapVisitor visitor)
throws ServiceException {
searchLdapOnReplica(base, filter.toFilterString(), returnAttrs, visitor);
}
private void searchZimbraLdap(String base, String query, String[] returnAttrs,
boolean useMaster, SearchLdapVisitor visitor) throws ServiceException {
SearchLdapOptions searchOptions = new SearchLdapOptions(base, query,
returnAttrs, SearchLdapOptions.SIZE_UNLIMITED, null,
ZSearchScope.SEARCH_SCOPE_SUBTREE, visitor);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.get(useMaster), LdapUsage.SEARCH);
zlc.searchPaged(searchOptions);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void waitForLdapServer() {
LdapClient.waitForLdapServer();
}
@Override
public void alwaysUseMaster() {
LdapClient.masterOnly();
}
@Override
public void dumpLdapSchema(PrintWriter writer) throws ServiceException {
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.GET_SCHEMA);
ZLdapSchema schema = zlc.getSchema();
for (ZLdapSchema.ZObjectClassDefinition oc : schema.getObjectClasses()) {
writer.println(oc.getName());
}
// TODO print more stuff
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get LDAP schema", e);
} finally {
LdapClient.closeContext(zlc);
}
}
/*
* returns if any one of addrs is an email address on the system
*/
private boolean addressExists(ZLdapContext zlc, String[] addrs)
throws ServiceException {
return addressExistsUnderDN(zlc, LdapConstants.DN_ROOT_DSE, addrs);
}
/*
* returns if any one of addrs is an email address under the specified baseDN
*/
private boolean addressExistsUnderDN(ZLdapContext zlc, String baseDN, String[] addrs)
throws ServiceException {
ZLdapFilter filter = filterFactory.addrsExist(addrs);
ZSearchControls searchControls = ZSearchControls.createSearchControls(
ZSearchScope.SEARCH_SCOPE_SUBTREE, 1, null);
try {
long count = helper.countEntries(baseDN, filter,
searchControls, zlc, LdapServerType.MASTER);
return count > 0;
} catch (LdapSizeLimitExceededException e) {
return true;
}
}
/*
* ==================
* Groups (static/dynamic neutral)
* ==================
*/
@Override
public Group createGroup(String name, Map<String, Object> attrs,
boolean dynamic) throws ServiceException{
return dynamic? createDynamicGroup(name, attrs) : createDistributionList(name, attrs);
}
@Override
public Group createDelegatedGroup(String name, Map<String, Object> attrs,
boolean dynamic, Account creator)
throws ServiceException {
if (creator == null) {
throw ServiceException.INVALID_REQUEST("must have a creator account", null);
}
Group group = dynamic?
createDynamicGroup(name, attrs, creator) :
createDistributionList(name, attrs, creator);
grantRight(TargetType.dl.getCode(), TargetBy.id, group.getId(),
GranteeType.GT_USER.getCode(), GranteeBy.id, creator.getId(), null,
Group.GroupOwner.GROUP_OWNER_RIGHT.getName(), null);
return group;
}
@Override
public void deleteGroup(String zimbraId) throws ServiceException {
Group group = getGroup(Key.DistributionListBy.id, zimbraId, true);
if (group == null) {
throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(zimbraId);
}
if (group.isDynamic()) {
deleteDynamicGroup((LdapDynamicGroup) group);
} else {
deleteDistributionList((LdapDistributionList) group);
}
}
@Override
public void renameGroup(String zimbraId, String newName) throws ServiceException {
Group group = getGroup(Key.DistributionListBy.id, zimbraId, true);
if (group == null) {
throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(zimbraId);
}
if (group.isDynamic()) {
renameDynamicGroup(zimbraId, newName);
} else {
renameDistributionList(zimbraId, newName);
}
}
@Override
public Group getGroup(Key.DistributionListBy keyType, String key) throws ServiceException {
return getGroup(keyType, key, false);
}
@Override
public Group getGroup(Key.DistributionListBy keyType, String key, boolean loadFromMaster)
throws ServiceException {
return getGroupInternal(keyType, key, false, loadFromMaster);
}
/*
* like getGroup(DistributionListBy keyType, String key)
* the difference are:
* - cached
* - entry returned only contains minimal group attrs
* - entry returned does not contain members (the member or zimbraMailForwardingAddress attribute)
*/
@Override
public Group getGroupBasic(Key.DistributionListBy keyType, String key)
throws ServiceException {
Group group = getGroupFromCache(keyType, key);
if (group != null) {
return group;
}
// fetch from LDAP
group = getGroupInternal(keyType, key, true, false);
// cache it
if (group != null) {
putInGroupCache(group);
}
return group;
}
@SuppressWarnings("unchecked")
@Override
public List getAllGroups(Domain domain) throws ServiceException {
SearchDirectoryOptions searchOpts = new SearchDirectoryOptions(domain);
searchOpts.setFilter(mDIT.filterGroupsByDomain(domain));
searchOpts.setTypes(ObjectType.distributionlists, ObjectType.dynamicgroups);
searchOpts.setSortOpt(SortOpt.SORT_ASCENDING);
List<NamedEntry> groups = (List<NamedEntry>) searchDirectoryInternal(searchOpts);
return groups;
}
@Override
public void addGroupMembers(Group group, String[] members) throws ServiceException {
if (group.isDynamic()) {
addDynamicGroupMembers((LdapDynamicGroup) group, members);
} else {
addDistributionListMembers((LdapDistributionList) group, members);
}
}
@Override
public void removeGroupMembers(Group group, String[] members) throws ServiceException {
if (group.isDynamic()) {
removeDynamicGroupMembers((LdapDynamicGroup)group, members, false);
} else {
removeDistributionListMembers((LdapDistributionList) group, members);
}
}
@Override
public void addGroupAlias(Group group, String alias) throws ServiceException {
addAliasInternal(group, alias);
allDLs.addGroup(group);
}
@Override
public void removeGroupAlias(Group group, String alias) throws ServiceException {
groupCache.remove(group);
removeAliasInternal(group, alias);
allDLs.removeGroup(alias);
}
@Override
public Set<String> getGroups(Account acct) throws ServiceException {
GroupMembership groupMembership = getGroupMembership(acct, false);
return Sets.newHashSet(groupMembership.groupIds());
}
/*
* only called from ProvUtil and GetAccountMembership SOAP handler.
* can't use getGroupMembership because it needs via.
*/
@Override
public List<Group> getGroups(Account acct, boolean directOnly, Map<String,String> via)
throws ServiceException {
// get static groups
List<DistributionList> dls = getDistributionLists(acct, directOnly, via);
// get dynamic groups
List<DynamicGroup> dynGroups = getContainingDynamicGroups(acct);
List<Group> groups = Lists.newArrayList();
groups.addAll(dls);
groups.addAll(dynGroups);
return groups;
}
@Override
public boolean inACLGroup(Account acct, String zimbraId) throws ServiceException {
GroupMembership membership = getGroupMembership(acct, false);
return membership.groupIds().contains(zimbraId);
}
@Override
public String[] getGroupMembers(Group group) throws ServiceException {
if (group instanceof DynamicGroup) {
DynamicGroup dynGroup = (DynamicGroup)group;
if (!dynGroup.isIsACLGroup()) {
return new String[0];
}
}
EntryCacheDataKey cacheKey = EntryCacheDataKey.GROUP_MEMBERS;
String[] members = (String[])group.getCachedData(cacheKey);
if (members != null) {
return members;
}
members = group.getAllMembers(); // should never be null
assert(members != null);
Arrays.sort(members);
// catch it
group.setCachedData(cacheKey, members);
return members;
}
@Override
public GroupMemberEmailAddrs getMemberAddrs(Group group) throws ServiceException {
// this is for mail delivery, always relaod the full group from LDAP
group = getGroup(DistributionListBy.id, group.getId());
GroupMemberEmailAddrs addrs = new GroupMemberEmailAddrs();
if (group.isDynamic()) {
LdapDynamicGroup ldapDynGroup = (LdapDynamicGroup)group;
if (ldapDynGroup.isIsACLGroup()) {
if (ldapDynGroup.hasExternalMembers()) {
// internal members
final List<String> internalMembers = Lists.newArrayList();
searchDynamicGroupInternalMemberDeliveryAddresses(null, group.getId(), internalMembers);
if (!internalMembers.isEmpty()) {
addrs.setInternalAddrs(internalMembers);
}
// external members
addrs.setExternalAddrs(ldapDynGroup.getStaticUnit().getMembersSet());
} else {
addrs.setGroupAddr(group.getName());
}
} else {
addrs.setGroupAddr(group.getName());
}
} else {
String[] members = getGroupMembers(group);
Set<String> internalMembers = Sets.newHashSet();
Set<String> externalMembers = Sets.newHashSet();
ZLdapContext zlc = LdapClient.getContext(LdapServerType.REPLICA, LdapUsage.SEARCH);
try {
for (String member : members) {
if (addressExists(zlc, new String[]{member})) {
internalMembers.add(member);
} else {
externalMembers.add(member);
}
}
} finally {
LdapClient.closeContext(zlc);
}
if (!externalMembers.isEmpty()) {
if (!internalMembers.isEmpty()) {
addrs.setInternalAddrs(internalMembers);
}
addrs.setExternalAddrs(externalMembers);
} else {
addrs.setGroupAddr(group.getName());
}
}
return addrs;
}
private void cleanGroupMembersCache(Group group) {
/*
* Fully loaded DLs(containing members attribute) are not cached
* (those obtained via Provisioning.getGroup().
*
* if the modified instance (the instance being passed in) is not the same
* instance in cache, clean the group members cache on the cached instance
*/
Group cachedInstance = getGroupFromCache(DistributionListBy.id, group.getId());
if (cachedInstance != null && group != cachedInstance) {
cachedInstance.removeCachedData(EntryCacheDataKey.GROUP_MEMBERS);
}
// also always clean it on the modified instance
group.removeCachedData(EntryCacheDataKey.GROUP_MEMBERS);
}
private Group getGroupInternal(Key.DistributionListBy keyType, String key,
boolean basicAttrsOnly, boolean loadFromMaster)
throws ServiceException {
switch(keyType) {
case id:
return getGroupById(key, null, basicAttrsOnly, loadFromMaster);
case name:
Group group = getGroupByName(key, null, basicAttrsOnly, loadFromMaster);
if (group == null) {
String localDomainAddr = getEmailAddrByDomainAlias(key);
if (localDomainAddr != null) {
group = getGroupByName(localDomainAddr, null, basicAttrsOnly, loadFromMaster);
}
}
return group;
default:
return null;
}
}
private Group getGroupById(String zimbraId, ZLdapContext zlc,
boolean basicAttrsOnly, boolean loadFromMaster)
throws ServiceException {
return getGroupByQuery(filterFactory.groupById(zimbraId), zlc, basicAttrsOnly, loadFromMaster);
}
private Group getGroupByName(String groupAddress, ZLdapContext zlc,
boolean basicAttrsOnly, boolean loadFromMaster)
throws ServiceException {
groupAddress = IDNUtil.toAsciiEmail(groupAddress);
return getGroupByQuery(filterFactory.groupByName(groupAddress), zlc, basicAttrsOnly, loadFromMaster);
}
private Group getGroupByQuery(ZLdapFilter filter, ZLdapContext initZlc,
boolean basicAttrsOnly, boolean loadFromMaster)
throws ServiceException {
try {
String[] returnAttrs = basicAttrsOnly ? BASIC_GROUP_ATTRS : null;
ZSearchResultEntry sr = helper.searchForEntry(
mDIT.mailBranchBaseDN(), filter, initZlc, loadFromMaster, returnAttrs);
if (sr != null) {
ZAttributes attrs = sr.getAttributes();
List<String> objectclass =
attrs.getMultiAttrStringAsList(Provisioning.A_objectClass, CheckBinary.NOCHECK);
if (objectclass.contains(AttributeClass.OC_zimbraDistributionList)) {
return makeDistributionList(sr.getDN(), attrs, basicAttrsOnly);
} else if (objectclass.contains(AttributeClass.OC_zimbraGroup)) {
return makeDynamicGroup(initZlc, sr.getDN(), attrs);
}
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getGroupByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup group via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
/*
* Set a home server for proxying purpose
* we now do this for all newly created groups instead of only for delegated groups
* For existing groups that don't have a zimbraMailHost:
* - admin soaps: just execute on the local server as before
* - user soap: throw exception
*/
private void setGroupHomeServer(ZMutableEntry entry, Account creator)
throws ServiceException {
//
Cos cosOfCreator = null;
if (creator != null) {
cosOfCreator = getCOS(creator);
}
addMailHost(entry, cosOfCreator, false);
}
/* ==================
* Dynamic Groups
* ==================
*/
private static final String DYNAMIC_GROUP_DYNAMIC_UNIT_NAME = "internal";
private static final String DYNAMIC_GROUP_STATIC_UNIT_NAME = "external";
@Override
public DynamicGroup createDynamicGroup(String groupAddress,
Map<String, Object> groupAttrs) throws ServiceException {
return createDynamicGroup(groupAddress, groupAttrs, null);
}
private String dynamicGroupDynamicUnitLocalpart(String dynamicGroupLocalpart) {
return dynamicGroupLocalpart + ".__internal__";
}
private String dynamicGroupStaticUnitLocalpart(String dynamicGroupLocalpart) {
return dynamicGroupLocalpart + ".__external__";
}
private DynamicGroup createDynamicGroup(String groupAddress,
Map<String, Object> groupAttrs, Account creator)
throws ServiceException {
SpecialAttrs specialAttrs = mDIT.handleSpecialAttrs(groupAttrs);
String baseDn = specialAttrs.getLdapBaseDn();
groupAddress = groupAddress.toLowerCase().trim();
EmailAddress addr = new EmailAddress(groupAddress);
String localPart = addr.getLocalPart();
String domainName = addr.getDomain();
domainName = IDNUtil.toAsciiDomainName(domainName);
groupAddress = EmailAddress.getAddress(localPart, domainName);
validEmailAddress(groupAddress);
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
callbackContext.setCreatingEntryName(groupAddress);
// remove zimbraIsACLGroup from attrs if provided, to avoid the immutable check
Object providedZimbraIsACLGroup = groupAttrs.get(A_zimbraIsACLGroup);
if (providedZimbraIsACLGroup != null) {
groupAttrs.remove(A_zimbraIsACLGroup);
}
AttributeManager.getInstance().preModify(groupAttrs, null, callbackContext, true);
// put zimbraIsACLGroup back
if (providedZimbraIsACLGroup != null) {
groupAttrs.put(A_zimbraIsACLGroup, providedZimbraIsACLGroup);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_DYNAMICGROUP);
Domain domain = getDomainByAsciiName(domainName, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(domainName);
}
if (!domain.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
String domainDN = ((LdapDomain) domain).getDN();
/*
* ====================================
* create the main dynamic group entry
* ====================================
*/
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(groupAttrs);
Set<String> ocs = LdapObjectClass.getGroupObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraId = LdapUtil.generateUUID();
// create a UUID for the static unit entry
String staticUnitZimbraId = LdapUtil.generateUUID();
String createTimestamp = DateUtil.toGeneralizedTime(new Date());
entry.setAttr(A_zimbraId, zimbraId);
entry.setAttr(A_zimbraCreateTimestamp, createTimestamp);
entry.setAttr(A_mail, groupAddress);
entry.setAttr(A_dgIdentity, LC.zimbra_ldap_userdn.value());
// unlike accounts (which have a zimbraMailDeliveryAddress for the primary,
// and zimbraMailAliases only for aliases), DLs use zimbraMailAlias for both.
// Postfix uses these two attributes to route mail, and zimbraMailDeliveryAddress
// indicates that something has a physical mailbox, which DLs don't.
entry.setAttr(A_zimbraMailAlias, groupAddress);
/*
// allow only users in the same domain
String memberURL = String.format("ldap:///%s??one?(zimbraMemberOf=%s)",
mDIT.domainDNToAccountBaseDN(domainDN), groupAddress);
*/
String specifiedIsACLGroup = entry.getAttrString(A_zimbraIsACLGroup);
boolean isACLGroup;
if (!entry.hasAttribute(A_memberURL)) {
String memberURL = LdapDynamicGroup.getDefaultMemberURL(zimbraId, staticUnitZimbraId);
entry.setAttr(Provisioning.A_memberURL, memberURL);
// memberURL is not provided, zimbraIsACLGroup must be either not specified,
// or specified to be TRUE;
if (specifiedIsACLGroup == null) {
entry.setAttr(A_zimbraIsACLGroup, ProvisioningConstants.TRUE);
} else if (ProvisioningConstants.FALSE.equals(specifiedIsACLGroup)) {
throw ServiceException.INVALID_REQUEST(
"No custom " + A_memberURL + " is provided, " +
A_zimbraIsACLGroup + " cannot be set to FALSE", null);
}
isACLGroup = true;
} else {
// if a custom memberURL is provided, zimbraIsACLGroup must also be specified
// and specifically set to FALSE
if (!ProvisioningConstants.FALSE.equals(specifiedIsACLGroup)) {
throw ServiceException.INVALID_REQUEST(
"Custom " + A_memberURL + " is provided, " +
A_zimbraIsACLGroup + " must be set to FALSE", null);
}
isACLGroup = false;
}
// by default a dynamic group is always created enabled
if (!entry.hasAttribute(Provisioning.A_zimbraMailStatus)) {
entry.setAttr(A_zimbraMailStatus, MAIL_STATUS_ENABLED);
}
String mailStatus = entry.getAttrString(A_zimbraMailStatus);
entry.setAttr(A_cn, localPart);
// entry.setAttr(A_uid, localPart); need to use uid if we move dynamic groups to the ou=people tree
setGroupHomeServer(entry, creator);
String dn = mDIT.dynamicGroupNameLocalPartToDN(localPart, domainDN);
entry.setDN(dn);
zlc.createEntry(entry);
if (isACLGroup) {
/*
* ===========================================================
* create the dynamic group unit entry, for internal addresses
* ===========================================================
*/
String dynamicUnitLocalpart = dynamicGroupDynamicUnitLocalpart(localPart);
String dynamicUnitAddr = EmailAddress.getAddress(dynamicUnitLocalpart, domainName);
entry = LdapClient.createMutableEntry();
ocs = LdapObjectClass.getGroupDynamicUnitObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String dynamicUnitZimbraId = LdapUtil.generateUUID();
entry.setAttr(A_cn, DYNAMIC_GROUP_DYNAMIC_UNIT_NAME);
entry.setAttr(A_zimbraId, dynamicUnitZimbraId);
entry.setAttr(A_zimbraGroupId, zimbraId); // id of the main group
entry.setAttr(A_zimbraCreateTimestamp, createTimestamp);
entry.setAttr(A_mail, dynamicUnitAddr);
entry.setAttr(A_zimbraMailAlias, dynamicUnitAddr);
entry.setAttr(A_zimbraMailStatus, mailStatus);
entry.setAttr(A_dgIdentity, LC.zimbra_ldap_userdn.value());
String memberURL = LdapDynamicGroup.getDefaultDynamicUnitMemberURL(zimbraId); // id of the main group
entry.setAttr(Provisioning.A_memberURL, memberURL);
String dynamicUnitDN = mDIT.dynamicGroupUnitNameToDN(
DYNAMIC_GROUP_DYNAMIC_UNIT_NAME, dn);
entry.setDN(dynamicUnitDN);
zlc.createEntry(entry);
/*
* ==========================================================
* create the static group unit entry, for external addresses
* ==========================================================
*/
entry = LdapClient.createMutableEntry();
ocs = LdapObjectClass.getGroupStaticUnitObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
entry.setAttr(A_cn, DYNAMIC_GROUP_STATIC_UNIT_NAME);
entry.setAttr(A_zimbraId, staticUnitZimbraId);
entry.setAttr(A_zimbraGroupId, zimbraId); // id of the main group
entry.setAttr(A_zimbraCreateTimestamp, createTimestamp);
String staticUnitDN = mDIT.dynamicGroupUnitNameToDN(
DYNAMIC_GROUP_STATIC_UNIT_NAME, dn);
entry.setDN(staticUnitDN);
zlc.createEntry(entry);
}
/*
* all is well, get the group by id
*/
DynamicGroup group = getDynamicGroupBasic(DistributionListBy.id, zimbraId, zlc);
if (group != null) {
AttributeManager.getInstance().postModify(groupAttrs, group, callbackContext);
removeExternalAddrsFromAllDynamicGroups(group.getAllAddrsSet(), zlc);
allDLs.addGroup(group);
} else {
throw ServiceException.FAILURE("unable to get dynamic group after creating LDAP entry: "+
groupAddress, null);
}
return group;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(groupAddress);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} finally {
LdapClient.closeContext(zlc);
}
}
private void deleteDynamicGroup(LdapDynamicGroup group) throws ServiceException {
String zimbraId = group.getId();
// make a copy of all addrs of this DL, after the delete all aliases on this dl
// object will be gone, but we need to remove them from the allgroups cache after the DL is deleted
Set<String> addrs = new HashSet<String>(group.getMultiAttrSet(Provisioning.A_mail));
/* ============ handle me ??
// remove the DL from all DLs
removeAddressFromAllDistributionLists(dl.getName()); // this doesn't throw any exceptions
*/
// delete all aliases of the group
String aliases[] = group.getAliases();
if (aliases != null) {
String groupName = group.getName();
for (int i=0; i < aliases.length; i++) {
// the primary name shows up in zimbraMailAlias on the entry, don't bother to remove
// this "alias" if it is the primary name, the entire entry will be deleted anyway.
if (!groupName.equalsIgnoreCase(aliases[i])) {
removeGroupAlias(group, aliases[i]); // this also removes each alias from any DLs
}
}
}
/*
// delete all grants granted to the DL
try {
RightCommand.revokeAllRights(this, GranteeType.GT_GROUP, zimbraId);
} catch (ServiceException e) {
// eat the exception and continue
ZimbraLog.account.warn("cannot revoke grants", e);
}
*/
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_DYNAMICGROUP);
String dn = group.getDN();
zlc.deleteChildren(dn);
zlc.deleteEntry(dn);
// remove zimbraMemberOf if this group from all accounts
deleteMemberOfOnAccounts(zlc, zimbraId);
groupCache.remove(group);
allDLs.removeGroup(addrs);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge group: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
PermissionCache.invalidateCache();
}
private void searchDynamicGroupInternalMembers(ZLdapContext zlc, String dynGroupId,
SearchLdapVisitor visitor)
throws ServiceException {
String base = mDIT.mailBranchBaseDN();
ZLdapFilter filter = filterFactory.accountByMemberOf(dynGroupId);
SearchLdapOptions searchOptions = new SearchLdapOptions(base, filter,
new String[]{A_zimbraMailDeliveryAddress, Provisioning.A_zimbraMemberOf},
SearchLdapOptions.SIZE_UNLIMITED,
null, ZSearchScope.SEARCH_SCOPE_SUBTREE, visitor);
zlc.searchPaged(searchOptions);
}
// TODO: change to ldif and do in background
private void deleteMemberOfOnAccounts(ZLdapContext zlc, String dynGroupId)
throws ServiceException {
final List<Account> accts = new ArrayList<Account>();
SearchLdapVisitor visitor = new SearchLdapVisitor(false) {
@Override
public void visit(String dn, IAttributes ldapAttrs) throws StopIteratingException {
Account acct;
try {
acct = makeAccountNoDefaults(dn, (ZAttributes) ldapAttrs);
accts.add(acct);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to make account " + dn, e);
}
}
};
searchDynamicGroupInternalMembers(zlc, dynGroupId, visitor);
// go through each DN and remove the zimbraMemberOf={dynGroupId} on the entry
// do in background?
for (Account acct : accts) {
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put("-" + Provisioning.A_zimbraMemberOf, dynGroupId);
modifyLdapAttrs(acct, zlc, attrs);
// remove the account from cache
// note: cannnot just removeFromCache(acct) because acct only
// contains the name, so id/alias/foreignPrincipal cached in NamedCache
// won't be cleared.
Account cached = getFromCache(AccountBy.name, acct.getName());
if (cached != null) {
removeFromCache(cached);
}
}
}
private void renameDynamicGroup(String zimbraId, String newEmail) throws ServiceException {
newEmail = IDNUtil.toAsciiEmail(newEmail);
validEmailAddress(newEmail);
boolean domainChanged = false;
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_DYNAMICGROUP);
LdapDynamicGroup group = (LdapDynamicGroup) getDynamicGroupById(zimbraId, zlc, false);
if (group == null) {
throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(zimbraId);
}
// prune cache
groupCache.remove(group);
String oldEmail = group.getName();
String oldDomain = EmailUtil.getValidDomainPart(oldEmail);
newEmail = newEmail.toLowerCase().trim();
String[] parts = EmailUtil.getLocalPartAndDomain(newEmail);
if (parts == null) {
throw ServiceException.INVALID_REQUEST("bad value for newName", null);
}
String newLocal = parts[0];
String newDomain = parts[1];
domainChanged = !oldDomain.equals(newDomain);
Domain domain = getDomainByAsciiName(newDomain, zlc);
if (domain == null) {
throw AccountServiceException.NO_SUCH_DOMAIN(newDomain);
}
if (domainChanged) {
// make sure the new domain is a local domain
if (!domain.isLocal()) {
throw ServiceException.INVALID_REQUEST("domain type must be local", null);
}
}
Map<String, Object> attrs = new HashMap<String, Object>();
ReplaceAddressResult replacedMails = replaceMailAddresses(group, Provisioning.A_mail, oldEmail, newEmail);
if (replacedMails.newAddrs().length == 0) {
// Set mail to newName if the account currently does not have a mail
attrs.put(Provisioning.A_mail, newEmail);
} else {
attrs.put(Provisioning.A_mail, replacedMails.newAddrs());
}
ReplaceAddressResult replacedAliases = replaceMailAddresses(group, Provisioning.A_zimbraMailAlias, oldEmail, newEmail);
if (replacedAliases.newAddrs().length > 0) {
attrs.put(Provisioning.A_zimbraMailAlias, replacedAliases.newAddrs());
String newDomainDN = mDIT.domainToAccountSearchDN(newDomain);
// check up front if any of renamed aliases already exists in the new domain (if domain also got changed)
if (domainChanged && addressExistsUnderDN(zlc, newDomainDN, replacedAliases.newAddrs())) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(newEmail);
}
}
ReplaceAddressResult replacedAllowAddrForDelegatedSender =
replaceMailAddresses(group, Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
oldEmail, newEmail);
if (replacedAllowAddrForDelegatedSender.newAddrs().length > 0) {
attrs.put(Provisioning.A_zimbraPrefAllowAddressForDelegatedSender,
replacedAllowAddrForDelegatedSender.newAddrs());
}
// the naming rdn
String rdnAttrName = mDIT.dynamicGroupNamingRdnAttr();
attrs.put(rdnAttrName, newLocal);
// move over the distribution list entry
String oldDn = group.getDN();
String newDn = mDIT.dynamicGroupDNRename(oldDn, newLocal, domain.getName());
boolean dnChanged = (!oldDn.equals(newDn));
if (dnChanged) {
// cn will be changed during renameEntry, so no need to modify it
// OpenLDAP is OK modifying it, as long as it matches the new DN, but
// InMemoryDirectoryServer does not like it.
attrs.remove(A_cn);
zlc.renameEntry(oldDn, newDn);
}
// re-get the entry after move
group = (LdapDynamicGroup) getDynamicGroupById(zimbraId, zlc, false);
// rename the distribution list and all it's renamed aliases to the new name in all distribution lists
// doesn't throw exceptions, just logs
/* should we do this for dyanmic groups?
renameAddressesInAllDistributionLists(oldEmail, newEmail, replacedAliases); // doesn't throw exceptions, just logs
*/
// MOVE OVER ALL aliases
// doesn't throw exceptions, just logs
if (domainChanged) {
String newUid = group.getAttr(rdnAttrName);
moveAliases(zlc, replacedAliases, newDomain, newUid, oldDn, newDn, oldDomain, newDomain);
}
// this is non-atomic. i.e., rename could succeed and updating A_mail
// could fail. So catch service exception here and log error
try {
// modify attrs on the mail entry
modifyAttrsInternal(group, zlc, attrs);
// modify attrs on the units
String dynamicUnitNewLocal = dynamicGroupDynamicUnitLocalpart(newLocal);
String dynamicUnitNewEmail = dynamicUnitNewLocal + "@" + newDomain;
String dynamicUnitDN = mDIT.dynamicGroupUnitNameToDN(
DYNAMIC_GROUP_DYNAMIC_UNIT_NAME, newDn);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.setAttr(A_mail, dynamicUnitNewEmail);
entry.setAttr(A_zimbraMailAlias, dynamicUnitNewEmail);
zlc.replaceAttributes(dynamicUnitDN, entry.getAttributes());
} catch (ServiceException e) {
ZimbraLog.account.error("dynamic group renamed to " + newLocal +
" but failed to move old name's LDAP attributes", e);
throw e;
}
removeExternalAddrsFromAllDynamicGroups(group.getAllAddrsSet(), zlc);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.DISTRIBUTION_LIST_EXISTS(newEmail);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename dynamic group: " + zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
if (domainChanged) {
PermissionCache.invalidateCache();
}
}
private DynamicGroup getDynamicGroupFromCache(Key.DistributionListBy keyType, String key) {
Group group = getGroupFromCache(keyType, key);
if (group instanceof DynamicGroup) {
return (DynamicGroup) group;
} else {
return null;
}
}
private DynamicGroup getDynamicGroupBasic(Key.DistributionListBy keyType, String key,
ZLdapContext zlc) throws ServiceException {
DynamicGroup dynGroup = getDynamicGroupFromCache(keyType, key);
if (dynGroup != null) {
return dynGroup;
}
switch(keyType) {
case id:
dynGroup = getDynamicGroupById(key, zlc, true);
break;
case name:
dynGroup = getDynamicGroupByName(key, zlc, true);
break;
}
if (dynGroup != null) {
putInGroupCache(dynGroup);
}
return dynGroup;
}
private DynamicGroup getDynamicGroupById(String zimbraId, ZLdapContext zlc, boolean basicAttrsOnly)
throws ServiceException {
return getDynamicGroupByQuery(filterFactory.dynamicGroupById(zimbraId), zlc, basicAttrsOnly);
}
private DynamicGroup getDynamicGroupByName(String groupAddress, ZLdapContext zlc,
boolean basicAttrsOnly)
throws ServiceException {
groupAddress = IDNUtil.toAsciiEmail(groupAddress);
return getDynamicGroupByQuery(filterFactory.dynamicGroupByName(groupAddress), zlc, basicAttrsOnly);
}
private DynamicGroup getDynamicGroupByQuery(ZLdapFilter filter, ZLdapContext initZlc, boolean basicAttrsOnly)
throws ServiceException {
try {
String[] returnAttrs = basicAttrsOnly ? BASIC_DYNAMIC_GROUP_ATTRS : null;
ZSearchResultEntry sr = helper.searchForEntry(mDIT.mailBranchBaseDN(), filter, initZlc, false, returnAttrs);
if (sr != null) {
return makeDynamicGroup(initZlc, sr.getDN(), sr.getAttributes());
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getDynamicGroupByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup group via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private void addDynamicGroupMembers(LdapDynamicGroup group, String[] members)
throws ServiceException {
if (!group.isIsACLGroup()) {
throw ServiceException.INVALID_REQUEST(
"cannot add members to dynamic group with custom memberURL", null);
}
String groupId = group.getId();
List<Account> accts = new ArrayList<Account>();
List<String> externalAddrs = new ArrayList<String>();
// check for errors, and put valid accts to the queue
for (String member : members) {
String memberName = member.toLowerCase();
memberName = IDNUtil.toAsciiEmail(memberName);
Account acct = get(AccountBy.name, memberName);
if (acct == null) {
// addr is not an account (could still be a group or group unit address
// on the system), will check by addressExists.
externalAddrs.add(memberName);
} else {
// is an account
Set<String> memberOf = acct.getMultiAttrSet(Provisioning.A_zimbraMemberOf);
if (!memberOf.contains(groupId)) {
accts.add(acct);
}
// else the addr is already in the group, just skip it, do not throw
}
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.ADD_GROUP_MEMBER);
// check non of the addrs in externalAddrs can be an email address
// on the system
if (!externalAddrs.isEmpty()) {
if (addressExists(zlc, externalAddrs.toArray(new String[externalAddrs.size()]))) {
throw ServiceException.INVALID_REQUEST("address cannot be a group: " +
Arrays.deepToString(externalAddrs.toArray()), null);
}
}
/*
* add internal members
*/
for (Account acct : accts) {
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put("+" + Provisioning.A_zimbraMemberOf, groupId);
modifyLdapAttrs(acct, zlc, attrs);
clearUpwardMembershipCache(acct);
}
/*
* add external members on the static unit
*/
LdapDynamicGroup.StaticUnit staticUnit = group.getStaticUnit();
Set<String> existingAddrs = staticUnit.getMembersSet();
List<String> addrsToAdd = Lists.newArrayList();
for (String addr : externalAddrs) {
if (!existingAddrs.contains(addr)) {
addrsToAdd.add(addr);
}
}
if (!addrsToAdd.isEmpty()) {
Map<String,String[]> attrs = new HashMap<String,String[]>();
attrs.put("+" + LdapDynamicGroup.StaticUnit.MEMBER_ATTR,
addrsToAdd.toArray(new String[addrsToAdd.size()]));
modifyLdapAttrs(staticUnit, zlc, attrs);
}
} finally {
LdapClient.closeContext(zlc);
}
PermissionCache.invalidateCache();
cleanGroupMembersCache(group);
}
private void removeDynamicGroupExternalMembers(LdapDynamicGroup group, String[] members)
throws ServiceException {
removeDynamicGroupMembers(group, members, true);
}
private void removeDynamicGroupMembers(LdapDynamicGroup group, String[] members, boolean externalOnly)
throws ServiceException {
if (!group.isIsACLGroup()) {
throw ServiceException.INVALID_REQUEST(
"cannot remove members from dynamic group with custom memberURL", null);
}
String groupId = group.getId();
List<Account> accts = new ArrayList<Account>();
List<String> externalAddrs = new ArrayList<String>();
HashSet<String> failed = new HashSet<String>();
// check for errors, and put valid accts to the queue
for (String member : members) {
String memberName = member.toLowerCase();
boolean isBadAddr = false;
try {
memberName = IDNUtil.toAsciiEmail(memberName);
} catch (ServiceException e) {
// if the addr is not a valid email address, maybe they want to
// remove a bogus addr that somehow got in, just let it through.
memberName = member;
isBadAddr = true;
}
// always add all addrs to "externalAddrs".
externalAddrs.add(memberName);
if (!externalOnly) {
Account acct = isBadAddr ? null : get(AccountBy.name, member);
if (acct != null) {
Set<String> memberOf = acct.getMultiAttrSet(Provisioning.A_zimbraMemberOf);
if (memberOf.contains(groupId)) {
accts.add(acct);
} else {
// else the addr is not in the group, throw exception
failed.add(memberName);
}
}
}
}
if (!failed.isEmpty()) {
StringBuilder sb = new StringBuilder();
Iterator<String> iter = failed.iterator();
while (true) {
sb.append(iter.next());
if (!iter.hasNext())
break;
sb.append(",");
}
throw AccountServiceException.NO_SUCH_MEMBER(group.getName(), sb.toString());
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.REMOVE_GROUP_MEMBER);
/*
* remove internal members
*/
for (Account acct : accts) {
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put("-" + Provisioning.A_zimbraMemberOf, groupId);
modifyLdapAttrs(acct, zlc, attrs);
clearUpwardMembershipCache(acct);
}
/*
* remove external members on the static unit
*/
LdapDynamicGroup.StaticUnit staticUnit = group.getStaticUnit();
Set<String> existingAddrs = staticUnit.getMembersSet();
List<String> addrsToRemove = Lists.newArrayList();
for (String addr : externalAddrs) {
if (existingAddrs.contains(addr)) {
addrsToRemove.add(addr);
}
}
if (!addrsToRemove.isEmpty()) {
Map<String,String[]> attrs = new HashMap<String,String[]>();
attrs.put("-" + LdapDynamicGroup.StaticUnit.MEMBER_ATTR,
addrsToRemove.toArray(new String[addrsToRemove.size()]));
modifyLdapAttrs(staticUnit, zlc, attrs);
}
} finally {
LdapClient.closeContext(zlc);
}
PermissionCache.invalidateCache();
cleanGroupMembersCache(group);
}
private List<DynamicGroup> getContainingDynamicGroups(Account acct) throws ServiceException {
List<DynamicGroup> groups = new ArrayList<DynamicGroup>();
Set<String> memberOf;
if (acct instanceof GuestAccount) {
memberOf = searchContainingDynamicGroupIdsForExternalAddress(acct.getName(), null);
} else if (acct.isIsExternalVirtualAccount()) {
memberOf = searchContainingDynamicGroupIdsForExternalAddress(acct.getExternalUserMailAddress(), null);
} else {
memberOf = acct.getMultiAttrSet(Provisioning.A_zimbraMemberOf);
}
for (String groupId : memberOf) {
DynamicGroup dynGroup = getDynamicGroupBasic(Key.DistributionListBy.id, groupId, null);
if (dynGroup != null && dynGroup.isIsACLGroup()) {
groups.add(dynGroup);
}
}
return groups;
}
/*
* returns zimbraId of dynamic groups containing addr as an external member.
*/
private Set<String> searchContainingDynamicGroupIdsForExternalAddress(
String addr, ZLdapContext initZlc) {
final Set<String> groupIds = Sets.newHashSet();
SearchLdapVisitor visitor = new SearchLdapVisitor(false) {
@Override
public void visit(String dn, IAttributes ldapAttrs)
throws StopIteratingException {
String groupId = null;
try {
groupId = ldapAttrs.getAttrString(A_zimbraGroupId);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get attr", e);
}
if (groupId != null) {
groupIds.add(groupId);
}
}
};
ZLdapContext zlc = initZlc;
try {
if (zlc == null) {
zlc = LdapClient.getContext(LdapServerType.REPLICA, LdapUsage.SEARCH);
}
String base = mDIT.mailBranchBaseDN();
ZLdapFilter filter =
filterFactory.dynamicGroupsStaticUnitByMemberAddr(addr);
SearchLdapOptions searchOptions = new SearchLdapOptions(base, filter,
new String[]{A_zimbraGroupId},
SearchLdapOptions.SIZE_UNLIMITED,
null, ZSearchScope.SEARCH_SCOPE_SUBTREE, visitor);
zlc.searchPaged(searchOptions);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to search dynamic groups for guest acct", e);
} finally {
if (initZlc == null) {
LdapClient.closeContext(zlc);
}
}
return groupIds;
}
/*
* remove addrs from all dynamic groups (i.e. static units of dynamic groups)
*
* Called whenever a new email address is created on the system
* (create/rename/add-alias of accounts and static/dynamic groups)
*/
private void removeExternalAddrsFromAllDynamicGroups(Set<String> addrs, ZLdapContext zlc)
throws ServiceException {
for (String addr : addrs) {
Set<String> memberOf = searchContainingDynamicGroupIdsForExternalAddress(addr, zlc);
for (String groupId : memberOf) {
DynamicGroup group = getDynamicGroupBasic(Key.DistributionListBy.id, groupId, zlc);
if (group != null) { // sanity check, should not be null
removeDynamicGroupExternalMembers((LdapDynamicGroup)group, new String[]{addr});
}
}
}
}
/*
* returns all internal and external member addresses of the DynamicGroup
*/
private List<String> searchDynamicGroupMembers(DynamicGroup group) throws ServiceException {
if (!group.isIsACLGroup()) {
throw ServiceException.INVALID_REQUEST(
"cannot search members to dynamic group with custom memberURL", null);
}
final List<String> members = Lists.newArrayList();
ZLdapContext zlc = null;
try {
// always use master to search for dynamic group members
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.SEARCH);
// search internal members
searchDynamicGroupInternalMemberDeliveryAddresses(zlc, group.getId(), members);
// add external members
LdapDynamicGroup.StaticUnit staticUnit = ((LdapDynamicGroup)group).getStaticUnit();
// need to refresh, the StaticUnit instance updated by add/remove
// dynamic group members may be the cached instance.
refreshEntry(staticUnit, zlc);
for (String extAddr : staticUnit.getMembers()) {
members.add(extAddr);
}
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to search dynamic group members", e);
} finally {
LdapClient.closeContext(zlc);
}
return members;
}
private void searchDynamicGroupInternalMemberDeliveryAddresses(
ZLdapContext initZlc, String dynGroupId, final Collection<String> result) {
SearchLdapVisitor visitor = new SearchLdapVisitor(false) {
@Override
public void visit(String dn, IAttributes ldapAttrs) throws StopIteratingException {
String addr = null;
try {
addr = ldapAttrs.getAttrString(Provisioning.A_zimbraMailDeliveryAddress);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get attr", e);
}
if (addr != null) {
result.add(addr);
}
}
};
ZLdapContext zlc = initZlc;
try {
if (zlc == null) {
// always use master to search for dynamic group members
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.SEARCH);
}
searchDynamicGroupInternalMembers(zlc, dynGroupId, visitor);
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to search dynamic group members", e);
} finally {
if (initZlc == null) {
LdapClient.closeContext(zlc);
}
}
}
public String[] getNonDefaultDynamicGroupMembers(DynamicGroup group) {
final List<String> members = Lists.newArrayList();
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.REPLICA, LdapUsage.GET_GROUP_MEMBER);
/*
* this DynamicGroup object must not be a basic group with minimum attrs,
* we need the member attribute
*/
String[] memberDNs = group.getMultiAttr(Provisioning.A_member);
final String[] addrToGet = new String[]{Provisioning.A_zimbraMailDeliveryAddress};
for (String memberDN : memberDNs) {
ZAttributes memberAddrs = zlc.getAttributes(memberDN, addrToGet);
String memberAddr = memberAddrs.getAttrString(Provisioning.A_zimbraMailDeliveryAddress);
if (memberAddr != null) {
members.add(memberAddr);
}
}
} catch (ServiceException e) {
ZimbraLog.account.warn("unable to get dynamic group members", e);
} finally {
LdapClient.closeContext(zlc);
}
return members.toArray(new String[members.size()]);
}
public String[] getDynamicGroupMembers(DynamicGroup group) throws ServiceException {
List<String> members = searchDynamicGroupMembers(group);
return members.toArray(new String[members.size()]);
}
public Set<String> getDynamicGroupMembersSet(DynamicGroup group) throws ServiceException {
List<String> members = searchDynamicGroupMembers(group);
return Sets.newHashSet(members);
}
/*
*
* UC service methods
*
*/
private UCService getUCServiceByQuery(ZLdapFilter filter, ZLdapContext initZlc)
throws ServiceException {
try {
ZSearchResultEntry sr = helper.searchForEntry(mDIT.ucServiceBaseDN(), filter, initZlc, false);
if (sr != null) {
return new LdapUCService(sr.getDN(), sr.getAttributes(), this);
}
} catch (LdapMultipleEntriesMatchedException e) {
throw AccountServiceException.MULTIPLE_ENTRIES_MATCHED("getUCServiceByQuery", e);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup ucservice via query: "+
filter.toFilterString() + " message:" + e.getMessage(), e);
}
return null;
}
private UCService getUCServiceById(String zimbraId, ZLdapContext zlc, boolean nocache)
throws ServiceException {
if (zimbraId == null) {
return null;
}
UCService s = null;
if (!nocache) {
s = ucServiceCache.getById(zimbraId);
}
if (s == null) {
s = getUCServiceByQuery(filterFactory.ucServiceById(zimbraId), zlc);
ucServiceCache.put(s);
}
return s;
}
private UCService getUCServiceByName(String name, boolean nocache) throws ServiceException {
if (!nocache) {
UCService s = ucServiceCache.getByName(name);
if (s != null) {
return s;
}
}
try {
String dn = mDIT.ucServiceNameToDN(name);
ZAttributes attrs = helper.getAttributes(LdapUsage.GET_UCSERVICE, dn);
LdapUCService s = new LdapUCService(dn, attrs, this);
ucServiceCache.put(s);
return s;
} catch (LdapEntryNotFoundException e) {
return null;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to lookup ucservice by name: "+name+" message: "+e.getMessage(), e);
}
}
@Override
public UCService createUCService(String name, Map<String, Object> attrs)
throws ServiceException {
name = name.toLowerCase().trim();
CallbackContext callbackContext = new CallbackContext(CallbackContext.Op.CREATE);
AttributeManager.getInstance().preModify(attrs, null, callbackContext, true);
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.CREATE_UCSERVICE);
ZMutableEntry entry = LdapClient.createMutableEntry();
entry.mapToAttrs(attrs);
Set<String> ocs = LdapObjectClass.getUCServiceObjectClasses(this);
entry.addAttr(A_objectClass, ocs);
String zimbraIdStr = LdapUtil.generateUUID();
entry.setAttr(A_zimbraId, zimbraIdStr);
entry.setAttr(A_zimbraCreateTimestamp, DateUtil.toGeneralizedTime(new Date()));
entry.setAttr(A_cn, name);
String dn = mDIT.ucServiceNameToDN(name);
entry.setDN(dn);
zlc.createEntry(entry);
UCService ucService = getUCServiceById(zimbraIdStr, zlc, true);
AttributeManager.getInstance().postModify(attrs, ucService, callbackContext);
return ucService;
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.SERVER_EXISTS(name);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to create ucservice: " + name, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public void deleteUCService(String zimbraId) throws ServiceException {
LdapUCService ucService = (LdapUCService) getUCServiceById(zimbraId, null, false);
if (ucService == null) {
throw AccountServiceException.NO_SUCH_UC_SERVICE(zimbraId);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.DELETE_UCSERVICE);
zlc.deleteEntry(ucService.getDN());
ucServiceCache.remove(ucService);
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to purge ucservice: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
@Override
public UCService get(UCServiceBy keyType, String key) throws ServiceException {
switch(keyType) {
case name:
return getUCServiceByName(key, false);
case id:
return getUCServiceById(key, null, false);
default:
return null;
}
}
@Override
public List<UCService> getAllUCServices() throws ServiceException {
List<UCService> result = new ArrayList<UCService>();
ZLdapFilter filter = filterFactory.allUCServices();
try {
ZSearchResultEnumeration ne = helper.searchDir(mDIT.ucServiceBaseDN(),
filter, ZSearchControls.SEARCH_CTLS_SUBTREE());
while (ne.hasMore()) {
ZSearchResultEntry sr = ne.next();
LdapUCService s = new LdapUCService(sr.getDN(), sr.getAttributes(), this);
result.add(s);
}
ne.close();
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to list all servers", e);
}
if (result.size() > 0) {
ucServiceCache.put(result, true);
}
Collections.sort(result);
return result;
}
@Override
public void renameUCService(String zimbraId, String newName) throws ServiceException {
LdapUCService ucService = (LdapUCService) getUCServiceById(zimbraId, null, false);
if (ucService == null) {
throw AccountServiceException.NO_SUCH_UC_SERVICE(zimbraId);
}
ZLdapContext zlc = null;
try {
zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.RENAME_UCSERVICE);
String newDn = mDIT.ucServiceNameToDN(newName);
zlc.renameEntry(ucService.getDN(), newDn);
ucServiceCache.remove(ucService);
} catch (LdapEntryAlreadyExistException nabe) {
throw AccountServiceException.UC_SERVICE_EXISTS(newName);
} catch (LdapException e) {
throw e;
} catch (AccountServiceException e) {
throw e;
} catch (ServiceException e) {
throw ServiceException.FAILURE("unable to rename ucservice: "+zimbraId, e);
} finally {
LdapClient.closeContext(zlc);
}
}
}
| mit |
maxcountryman/flask-uploads | flask_uploads.py | 19724 | # -*- coding: utf-8 -*-
"""
flaskext.uploads
================
This module provides upload support for Flask. The basic pattern is to set up
an `UploadSet` object and upload your files to it.
:copyright: 2010 Matthew "LeafStorm" Frazier
:license: MIT/X11, see LICENSE for details
"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
import os.path
import posixpath
from flask import current_app, send_from_directory, abort, url_for
from itertools import chain
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from flask import Blueprint
# Extension presets
#: This just contains plain text files (.txt).
TEXT = ('txt',)
#: This contains various office document formats (.rtf, .odf, .ods, .gnumeric,
#: .abw, .doc, .docx, .xls, .xlsx and .pdf). Note that the macro-enabled versions
#: of Microsoft Office 2007 files are not included.
DOCUMENTS = tuple('rtf odf ods gnumeric abw doc docx xls xlsx pdf'.split())
#: This contains basic image types that are viewable from most browsers (.jpg,
#: .jpe, .jpeg, .png, .gif, .svg, .bmp and .webp).
IMAGES = tuple('jpg jpe jpeg png gif svg bmp webp'.split())
#: This contains audio file types (.wav, .mp3, .aac, .ogg, .oga, and .flac).
AUDIO = tuple('wav mp3 aac ogg oga flac'.split())
#: This is for structured data files (.csv, .ini, .json, .plist, .xml, .yaml,
#: and .yml).
DATA = tuple('csv ini json plist xml yaml yml'.split())
#: This contains various types of scripts (.js, .php, .pl, .py .rb, and .sh).
#: If your Web server has PHP installed and set to auto-run, you might want to
#: add ``php`` to the DENY setting.
SCRIPTS = tuple('js php pl py rb sh'.split())
#: This contains archive and compression formats (.gz, .bz2, .zip, .tar,
#: .tgz, .txz, and .7z).
ARCHIVES = tuple('gz bz2 zip tar tgz txz 7z'.split())
#: This contains nonexecutable source files - those which need to be
#: compiled or assembled to binaries to be used. They are generally safe to
#: accept, as without an existing RCE vulnerability, they cannot be compiled,
#: assembled, linked, or executed. Supports C, C++, Ada, Rust, Go (Golang),
#: FORTRAN, D, Java, C Sharp, F Sharp (compiled only), COBOL, Haskell, and
#: assembly.
SOURCE = tuple(('c cpp c++ h hpp h++ cxx hxx hdl ' # C/C++
+ 'ada ' # Ada
+ 'rs ' # Rust
+ 'go ' # Go
+ 'f for f90 f95 f03 ' # FORTRAN
+ 'd dd di ' # D
+ 'java ' # Java
+ 'hs ' # Haskell
+ 'cs ' # C Sharp
+ 'fs ' # F Sharp compiled source (NOT .fsx, which is interactive-ready)
+ 'cbl cob ' # COBOL
+ 'asm s ' # Assembly
).split())
#: This contains shared libraries and executable files (.so, .exe and .dll).
#: Most of the time, you will not want to allow this - it's better suited for
#: use with `AllExcept`.
EXECUTABLES = tuple('so exe dll'.split())
#: The default allowed extensions - `TEXT`, `DOCUMENTS`, `DATA`, and `IMAGES`.
DEFAULTS = TEXT + DOCUMENTS + IMAGES + DATA
class UploadNotAllowed(Exception):
"""
This exception is raised if the upload was not allowed. You should catch
it in your view code and display an appropriate message to the user.
"""
def tuple_from(*iters):
return tuple(itertools.chain(*iters))
def extension(filename):
ext = os.path.splitext(filename)[1]
if ext == '':
# add non-ascii filename support
ext = os.path.splitext(filename)[0]
if ext.startswith('.'):
# os.path.splitext retains . separator
ext = ext[1:]
return ext
def lowercase_ext(filename):
"""
This is a helper used by UploadSet.save to provide lowercase extensions for
all processed files, to compare with configured extensions in the same
case.
.. versionchanged:: 0.1.4
Filenames without extensions are no longer lowercased, only the
extension is returned in lowercase, if an extension exists.
:param filename: The filename to ensure has a lowercase extension.
"""
if '.' in filename:
main, ext = os.path.splitext(filename)
return main + ext.lower()
# For consistency with os.path.splitext,
# do not treat a filename without an extension as an extension.
# That is, do not return filename.lower().
return filename
def addslash(url):
if url.endswith('/'):
return url
return url + '/'
def patch_request_class(app, size=64 * 1024 * 1024):
"""
By default, Flask will accept uploads to an arbitrary size. While Werkzeug
switches uploads from memory to a temporary file when they hit 500 KiB,
it's still possible for someone to overload your disk space with a
gigantic file.
This patches the app's request class's
`~werkzeug.BaseRequest.max_content_length` attribute so that any upload
larger than the given size is rejected with an HTTP error.
.. note::
In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
setting, without patching the request class. To emulate this behavior,
you can pass `None` as the size (you must pass it explicitly). That is
the best way to call this function, as it won't break the Flask 0.6
functionality if it exists.
.. versionchanged:: 0.1.1
:param app: The app to patch the request class of.
:param size: The maximum size to accept, in bytes. The default is 64 MiB.
If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
setting will be used to patch.
"""
if size is None:
if isinstance(app.request_class.__dict__['max_content_length'],
property):
return
size = app.config.get('MAX_CONTENT_LENGTH')
reqclass = app.request_class
patched = type(reqclass.__name__, (reqclass,),
{'max_content_length': size})
app.request_class = patched
def config_for_set(uset, app, defaults=None):
"""
This is a helper function for `configure_uploads` that extracts the
configuration for a single set.
:param uset: The upload set.
:param app: The app to load the configuration from.
:param defaults: A dict with keys `url` and `dest` from the
`UPLOADS_DEFAULT_DEST` and `DEFAULT_UPLOADS_URL`
settings.
"""
config = app.config
prefix = 'UPLOADED_%s_' % uset.name.upper()
using_defaults = False
if defaults is None:
defaults = dict(dest=None, url=None)
allow_extns = tuple(config.get(prefix + 'ALLOW', ()))
deny_extns = tuple(config.get(prefix + 'DENY', ()))
destination = config.get(prefix + 'DEST')
base_url = config.get(prefix + 'URL')
if destination is None:
# the upload set's destination wasn't given
if uset.default_dest:
# use the "default_dest" callable
destination = uset.default_dest(app)
if destination is None: # still
# use the default dest from the config
if defaults['dest'] is not None:
using_defaults = True
destination = os.path.join(defaults['dest'], uset.name)
else:
raise RuntimeError("no destination for set %s" % uset.name)
if base_url is None and using_defaults and defaults['url']:
base_url = addslash(defaults['url']) + uset.name + '/'
return UploadConfiguration(destination, base_url, allow_extns, deny_extns)
def configure_uploads(app, upload_sets):
"""
Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with different upload sets.
.. versionchanged:: 0.1.3
The uploads module/blueprint will only be registered if it is needed
to serve the upload sets.
:param app: The `~flask.Flask` instance to get the configuration from.
:param upload_sets: The `UploadSet` instances to configure.
"""
if isinstance(upload_sets, UploadSet):
upload_sets = (upload_sets,)
if not hasattr(app, 'upload_set_config'):
app.upload_set_config = {}
set_config = app.upload_set_config
defaults = dict(dest=app.config.get('UPLOADS_DEFAULT_DEST'),
url=app.config.get('UPLOADS_DEFAULT_URL'))
for uset in upload_sets:
config = config_for_set(uset, app, defaults)
set_config[uset.name] = config
should_serve = any(s.base_url is None for s in set_config.values())
if '_uploads' not in app.blueprints and should_serve:
app.register_blueprint(uploads_mod)
class All(object):
"""
This type can be used to allow all extensions. There is a predefined
instance named `ALL`.
"""
def __contains__(self, item):
return True
#: This "contains" all items. You can use it to allow all extensions to be
#: uploaded.
ALL = All()
class AllExcept(object):
"""
This can be used to allow all file types except certain ones. For example,
to ban .exe and .iso files, pass::
AllExcept(('exe', 'iso'))
to the `UploadSet` constructor as `extensions`. You can use any container,
for example::
AllExcept(SCRIPTS + EXECUTABLES)
"""
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item not in self.items
class UploadConfiguration(object):
"""
This holds the configuration for a single `UploadSet`. The constructor's
arguments are also the attributes.
:param destination: The directory to save files to.
:param base_url: The URL (ending with a /) that files can be downloaded
from. If this is `None`, Flask-Uploads will serve the
files itself.
:param allow: A list of extensions to allow, even if they're not in the
`UploadSet` extensions list.
:param deny: A list of extensions to deny, even if they are in the
`UploadSet` extensions list.
"""
def __init__(self, destination, base_url=None, allow=(), deny=()):
self.destination = destination
self.base_url = base_url
self.allow = allow
self.deny = deny
@property
def tuple(self):
return (self.destination, self.base_url, self.allow, self.deny)
def __eq__(self, other):
return self.tuple == other.tuple
class UploadSet(object):
"""
This represents a single set of uploaded files. Each upload set is
independent of the others. This can be reused across multiple application
instances, as all configuration is stored on the application object itself
and found with `flask.current_app`.
:param name: The name of this upload set. It defaults to ``files``, but
you can pick any alphanumeric name you want. (For simplicity,
it's best to use a plural noun.)
:param extensions: The extensions to allow uploading in this set. The
easiest way to do this is to add together the extension
presets (for example, ``TEXT + DOCUMENTS + IMAGES``).
It can be overridden by the configuration with the
`UPLOADED_X_ALLOW` and `UPLOADED_X_DENY` configuration
parameters. The default is `DEFAULTS`.
:param default_dest: If given, this should be a callable. If you call it
with the app, it should return the default upload
destination path for that app.
"""
def __init__(self, name='files', extensions=DEFAULTS, default_dest=None):
if not name.isalnum():
raise ValueError("Name must be alphanumeric (no underscores)")
self.name = name
self.extensions = extensions
self._config = None
self.default_dest = default_dest
@property
def config(self):
"""
This gets the current configuration. By default, it looks up the
current application and gets the configuration from there. But if you
don't want to go to the full effort of setting an application, or it's
otherwise outside of a request context, set the `_config` attribute to
an `UploadConfiguration` instance, then set it back to `None` when
you're done.
"""
if self._config is not None:
return self._config
try:
return current_app.upload_set_config[self.name]
except AttributeError:
raise RuntimeError("cannot access configuration outside request")
def url(self, filename):
"""
This function gets the URL a file uploaded to this set would be
accessed at. It doesn't check whether said file exists.
:param filename: The filename to return the URL for.
"""
base = self.config.base_url
if base is None:
return url_for('_uploads.uploaded_file', setname=self.name,
filename=filename, _external=True)
else:
return base + filename
def path(self, filename, folder=None):
"""
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to.
"""
if folder is not None:
target_folder = os.path.join(self.config.destination, folder)
else:
target_folder = self.config.destination
return os.path.join(target_folder, filename)
def file_allowed(self, storage, basename):
"""
This tells whether a file is allowed. It should return `True` if the
given `werkzeug.FileStorage` object can be saved with the given
basename, and `False` if it can't. The default implementation just
checks the extension, so you can override this if you want.
:param storage: The `werkzeug.FileStorage` to check.
:param basename: The basename it will be saved under.
"""
return self.extension_allowed(extension(basename))
def extension_allowed(self, ext):
"""
This determines whether a specific extension is allowed. It is called
by `file_allowed`, so if you override that but still want to check
extensions, call back into this.
:param ext: The extension to check, without the dot.
"""
return ((ext in self.config.allow) or
(ext in self.extensions and ext not in self.config.deny))
def get_basename(self, filename):
return lowercase_ext(secure_filename(filename))
def save(self, storage, folder=None, name=None):
"""
This saves a `werkzeug.FileStorage` into this upload set. If the
upload is not allowed, an `UploadNotAllowed` error will be raised.
Otherwise, the file will be saved and its name (including the folder)
will be returned.
:param storage: The uploaded file to save.
:param folder: The subfolder within the upload set to save to.
:param name: The name to save the file as. If it ends with a dot, the
file's extension will be appended to the end. (If you
are using `name`, you can include the folder in the
`name` instead of explicitly using `folder`, i.e.
``uset.save(file, name="someguy/photo_123.")``
"""
if not isinstance(storage, FileStorage):
raise TypeError("storage must be a werkzeug.FileStorage")
if folder is None and name is not None and "/" in name:
folder, name = os.path.split(name)
basename = self.get_basename(storage.filename)
if not self.file_allowed(storage, basename):
raise UploadNotAllowed()
if name:
if name.endswith('.'):
basename = name + extension(basename)
else:
basename = name
if folder:
target_folder = os.path.join(self.config.destination, folder)
else:
target_folder = self.config.destination
if not os.path.exists(target_folder):
os.makedirs(target_folder)
if os.path.exists(os.path.join(target_folder, basename)):
basename = self.resolve_conflict(target_folder, basename)
target = os.path.join(target_folder, basename)
storage.save(target)
if folder:
return posixpath.join(folder, basename)
else:
return basename
def resolve_conflict(self, target_folder, basename):
"""
If a file with the selected name already exists in the target folder,
this method is called to resolve the conflict. It should return a new
basename for the file.
The default implementation splits the name and extension and adds a
suffix to the name consisting of an underscore and a number, and tries
that until it finds one that doesn't exist.
:param target_folder: The absolute path to the target.
:param basename: The file's original basename.
"""
name, ext = os.path.splitext(basename)
count = 0
while True:
count = count + 1
newname = '%s_%d%s' % (name, count, ext)
if not os.path.exists(os.path.join(target_folder, newname)):
return newname
uploads_mod = Blueprint('_uploads', __name__, url_prefix='/_uploads')
@uploads_mod.route('/<setname>/<path:filename>')
def uploaded_file(setname, filename):
config = current_app.upload_set_config.get(setname)
if config is None:
abort(404)
return send_from_directory(config.destination, filename)
class TestingFileStorage(FileStorage):
"""
This is a helper for testing upload behavior in your application. You
can manually create it, and its save method is overloaded to set `saved`
to the name of the file it was saved to. All of these parameters are
optional, so only bother setting the ones relevant to your application.
:param stream: A stream. The default is an empty stream.
:param filename: The filename uploaded from the client. The default is the
stream's name.
:param name: The name of the form field it was loaded from. The default is
`None`.
:param content_type: The content type it was uploaded as. The default is
``application/octet-stream``.
:param content_length: How long it is. The default is -1.
:param headers: Multipart headers as a `werkzeug.Headers`. The default is
`None`.
"""
def __init__(self, stream=None, filename=None, name=None,
content_type='application/octet-stream', content_length=-1,
headers=None):
FileStorage.__init__(self, stream, filename, name=name,
content_type=content_type, content_length=content_length,
headers=None)
self.saved = None
def save(self, dst, buffer_size=16384):
"""
This marks the file as saved by setting the `saved` attribute to the
name of the file it was saved to.
:param dst: The file to save to.
:param buffer_size: Ignored.
"""
if isinstance(dst, string_types):
self.saved = dst
else:
self.saved = dst.name
| mit |
u-renda/nic_api | application/controllers/Cart_total.php | 8504 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH.'/libraries/REST_Controller.php';
class Cart_total extends REST_Controller {
function __construct()
{
parent::__construct();
$this->load->model('cart_total_model', 'the_model');
}
function create_post()
{
$this->benchmark->mark('code_start');
$validation = 'ok';
$unique_code = filter(trim($this->post('unique_code')));
$total = filter(trim($this->post('total')));
$status = filter(trim($this->post('status')));
$data = array();
if ($unique_code == FALSE)
{
$data['unique_code'] = 'required';
$validation = 'error';
$code = 400;
}
if ($total == FALSE)
{
$data['total'] = 'required';
$validation = 'error';
$code = 400;
}
if ($status == FALSE)
{
$data['status'] = 'required';
$validation = 'error';
$code = 400;
}
if (in_array($status, $this->config->item('default_cart_total_status')) == FALSE && $status == TRUE)
{
$data['status'] = 'wrong value';
$validation = 'error';
$code = 400;
}
if ($validation == 'ok')
{
$param = array();
$param['unique_code'] = $unique_code;
$param['total'] = $total;
$param['status'] = $status;
$param['created_date'] = date('Y-m-d H:i:s');
$param['updated_date'] = date('Y-m-d H:i:s');
$query = $this->the_model->create($param);
if ($query > 0)
{
$data['create'] = 'success';
$validation = 'ok';
$code = 200;
}
else
{
$data['create'] = 'failed';
$validation = 'error';
$code = 400;
}
}
$rv = array();
$rv['message'] = $validation;
$rv['code'] = $code;
$rv['result'] = $data;
$this->benchmark->mark('code_end');
$rv['load'] = $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
$this->response($rv, $code);
}
function delete_post()
{
$this->benchmark->mark('code_start');
$validation = 'ok';
$id_cart_total = filter($this->post('id_cart_total'));
$data = array();
if ($id_cart_total == FALSE)
{
$data['id_cart_total'] = 'required';
$validation = "error";
$code = 400;
}
if ($validation == "ok")
{
$query = $this->the_model->info(array('id_cart_total' => $id_cart_total));
if ($query->num_rows() > 0)
{
$delete = $this->the_model->delete($id_cart_total);
if ($delete > 0)
{
$data['delete'] = 'success';
$validation = "ok";
$code = 200;
}
else
{
$data['delete'] = 'failed';
$validation = "error";
$code = 400;
}
}
else
{
$data['id_cart_total'] = 'not found';
$validation = "error";
$code = 400;
}
}
$rv = array();
$rv['message'] = $validation;
$rv['code'] = $code;
$rv['result'] = $data;
$this->benchmark->mark('code_end');
$rv['load'] = $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
$this->response($rv, $code);
}
function info_get()
{
$this->benchmark->mark('code_start');
$validation = 'ok';
$id_cart_total = filter($this->get('id_cart_total'));
$unique_code = filter($this->get('unique_code'));
$status = filter($this->get('status'));
$data = array();
if ($id_cart_total == FALSE && $unique_code == FALSE)
{
$data['id_cart_total'] = 'required';
$validation = 'error';
$code = 400;
}
if ($validation == 'ok')
{
$param = array();
if ($id_cart_total != '')
{
$param['id_cart_total'] = $id_cart_total;
}
else
{
$param['unique_code'] = $unique_code;
}
if ($status != '')
{
$param['status'] = $status;
}
$query = $this->the_model->info($param);
if ($query->num_rows() > 0)
{
$row = $query->row();
$data = array(
'id_cart_total' => $row->id_cart_total,
'unique_code' => $row->unique_code,
'total' => intval($row->total),
'status' => intval($row->status),
'created_date' => $row->created_date,
'updated_date' => $row->updated_date
);
$validation = 'ok';
$code = 200;
}
else
{
$data['id_cart_total'] = 'Not Found';
$validation = 'error';
$code = 400;
}
}
$rv = array();
$rv['message'] = $validation;
$rv['code'] = $code;
$rv['result'] = $data;
$this->benchmark->mark('code_end');
$rv['load'] = $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
$this->response($rv, $code);
}
function lists_get()
{
$this->benchmark->mark('code_start');
$offset = filter(trim(intval($this->get('offset'))));
$limit = filter(trim(intval($this->get('limit'))));
$order = filter(trim(strtolower($this->get('order'))));
$sort = filter(trim(strtolower($this->get('sort'))));
$status = filter(trim($this->get('status')));
if ($limit == TRUE && $limit < 20)
{
$limit = $limit;
}
elseif ($limit == TRUE && in_array($this->rest->key, $this->config->item('allow_api_key')))
{
$limit = $limit;
}
else
{
$limit = 20;
}
if ($offset == TRUE)
{
$offset = $offset;
}
else
{
$offset = 0;
}
if (in_array($order, $this->config->item('default_cart_total_order')) && ($order == TRUE))
{
$order = $order;
}
else
{
$order = 'created_date';
}
if (in_array($sort, $this->config->item('default_sort')) && ($sort == TRUE))
{
$sort = $sort;
}
else
{
$sort = 'desc';
}
if (in_array($status, $this->config->item('default_cart_total_status')) && ($status == TRUE))
{
$status = $status;
}
$param = array();
$param2 = array();
if ($status == TRUE)
{
$param['status'] = intval($status);
$param2['status'] = intval($status);
}
$param['limit'] = $limit;
$param['offset'] = $offset;
$param['order'] = $order;
$param['sort'] = $sort;
$query = $this->the_model->lists($param);
$total = $this->the_model->lists_count($param2);
$data = array();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = array(
'id_cart_total' => $row->id_cart_total,
'unique_code' => $row->unique_code,
'total' => intval($row->total),
'status' => intval($row->status),
'created_date' => $row->created_date,
'updated_date' => $row->updated_date
);
}
}
$rv = array();
$rv['message'] = 'ok';
$rv['code'] = 200;
$rv['limit'] = intval($limit);
$rv['offset'] = intval($offset);
$rv['total'] = intval($total);
$rv['count'] = count($data);
$rv['result'] = $data;
$this->benchmark->mark('code_end');
$rv['load'] = $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
$this->response($rv, $rv['code']);
}
function update_post()
{
$this->benchmark->mark('code_start');
$validation = 'ok';
$id_cart_total = filter($this->post('id_cart_total'));
$unique_code = filter(trim($this->post('unique_code')));
$total = filter(trim($this->post('total')));
$status = filter(trim($this->post('status')));
$data = array();
if ($id_cart_total == FALSE)
{
$data['id_cart_total'] = 'required';
$validation = 'error';
$code = 400;
}
if (in_array($status, $this->config->item('default_cart_total_status')) == FALSE && $status == TRUE)
{
$data['status'] = 'wrong value';
$validation = 'error';
$code = 400;
}
if ($validation == 'ok')
{
$query = $this->the_model->info(array('id_cart_total' => $id_cart_total));
if ($query->num_rows() > 0)
{
$param = array();
if ($unique_code == TRUE)
{
$param['unique_code'] = $unique_code;
}
if ($total == TRUE)
{
$param['total'] = $total;
}
if ($status == TRUE)
{
$param['status'] = $status;
}
if ($param == TRUE)
{
$param['updated_date'] = date('Y-m-d H:i:s');
$update = $this->the_model->update($id_cart_total, $param);
if ($update > 0)
{
$data['update'] = 'success';
$validation = 'ok';
$code = 200;
}
}
else
{
$data['update'] = 'failed';
$validation = 'error';
$code = 400;
}
}
else
{
$data['id_cart_total'] = 'not found';
$validation = 'error';
$code = 400;
}
}
$rv = array();
$rv['message'] = $validation;
$rv['code'] = $code;
$rv['result'] = $data;
$this->benchmark->mark('code_end');
$rv['load'] = $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
$this->response($rv, $code);
}
}
| mit |
Syncano/syncano-cli | syncano_cli/parse_to_syncano/moses.py | 2196 | # -*- coding: utf-8 -*-
import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES
def force_config_value(config, config_var_name, section='P2S'):
prompter = Prompter()
config_var = prompter.prompt('{}'.format(config_var_name))
if not config.has_section(section):
config.add_section(section)
config.set(section, config_var_name, config_var)
def check_config_value(config, config_var_name, silent, section='P2S'):
formatter = Formatter()
if not config.has_option(section, config_var_name):
force_config_value(config, config_var_name)
else:
if not silent:
formatter.write("{config_var_name}: {config_var}".format(
config_var_name=click.style(config_var_name, fg=ColorSchema.PROMPT),
config_var=click.style(config.get(section, config_var_name), fg=ColorSchema.INFO)
))
def write_config_to_file(config):
with open(ACCOUNT_CONFIG_PATH, 'wt') as config_file:
config.write(config_file)
def check_configuration(config, silent=False):
for config_var_name in CONFIG_VARIABLES_NAMES:
check_config_value(config, config_var_name, silent=silent)
write_config_to_file(config)
def force_configuration_overwrite(config):
for config_var_name in CONFIG_VARIABLES_NAMES:
force_config_value(config, config_var_name)
write_config_to_file(config)
def print_configuration(config):
formatter = Formatter()
if not config.has_section('P2S'):
config.add_section('P2S')
for config_var_name in CONFIG_VARIABLES_NAMES:
if not config.has_option('P2S', config_var_name):
config_var = "-- NOT SET --"
else:
config_var = config.get('P2S', config_var_name)
formatter.write("{config_var_name}: {config_var}".format(
config_var_name=click.style(config_var_name, fg=ColorSchema.PROMPT),
config_var=click.style(config_var, fg=ColorSchema.INFO)
))
| mit |
justphil/angular-es6-components-seed | karma.conf.js | 4148 | var istanbul = require('browserify-istanbul'),
isparta = require('isparta'),
gulpMainConfig = require('./gulp/config');
// Karma configuration for unit tests
module.exports = function (config) {
var srcDir = gulpMainConfig.sourceDirectory.substr(2);
var karmaConfig = {
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine-jquery', 'jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
// PhantomJS v1.X doesn't support Function.prototype.bind. So, we need a polyfill for that.
'node_modules/phantomjs-polyfill/bind-polyfill.js',
srcDir + '/_bootstrap/_bootstrap.js', // our SPA code
srcDir + '/**/*.spec.js', // our unit tests
srcDir + '/**/*.html' // our templates (for unit testing directives)
],
// list of files to exclude
exclude: [
srcDir + '/index.html'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'junit', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
preprocessors: {},
ngHtml2JsPreprocessor: {
stripPrefix: srcDir + '/',
prependPrefix: 'templates/',
moduleName: 'ng'
},
browserify: {
debug: true,
extensions: ['.js'],
transform: [
['babelify', {presets: ['es2015']}],
// We use istanbul programmatically due to a Karma coverage issue in conjunction with Browserify.
// See https://github.com/karma-runner/karma-coverage/issues/157 for details.
istanbul({
instrumenter: isparta,
ignore: ['**/*.spec.js', '**/vendor/**/*.js', '**/bower_npm_integrations/**/*.js'],
defaultIgnore: true // node_modules will be ignored by default
})
]
},
coverageReporter: {
reporters: [
{
type: 'html',
dir: '.tmp/reports/coverage/html/'
},
{
type: 'lcovonly',
dir: '.tmp/reports/coverage/',
subdir: 'lcov/'
}
],
watermarks: {
statements: [65, 85],
functions: [65, 85],
branches: [65, 85],
lines: [65, 85]
}
},
junitReporter: {
outputDir: 'target/surefire-reports/'
}
};
karmaConfig.preprocessors[srcDir + '/**/*.html'] = 'ng-html2js';
karmaConfig.preprocessors[srcDir + '/**/*.js'] = 'browserify';
/**
* Although the specified pattern doesn't match any files
* we need this line to make IntelliJ's Karma coverage integration work.
* If there'll be more time we have to investigate further why this lines works...
*/
karmaConfig.preprocessors[srcDir + '/this path does not care/*.js'] = 'coverage';
config.set(karmaConfig);
};
| mit |
mmirhoseini/fyber_mobile_offers | core-lib/src/main/java/com/mirhoseini/fyber/di/scope/LoginScope.java | 273 | package com.mirhoseini.fyber.di.scope;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
/**
* Created by Mohsen on 30/09/2016.
*/
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginScope {
}
| mit |
dadooda/ori | lib/ori/library.rb | 1383 | require "set"
module ORI
# ri lookup library.
class Library #:nodoc:
# Mask of ri command to fetch content. Example:
#
# ri -T -f ansi %s
attr_accessor :frontend
# Shell escape mode. <tt>:unix</tt> or <tt>:windows</tt>.
attr_accessor :shell_escape
def initialize(attrs = {})
@cache = {}
attrs.each {|k, v| send("#{k}=", v)}
end
# Lookup an article.
#
# lookup("Kernel#puts") # => content or nil.
def lookup(topic)
if @cache.has_key? topic
@cache[topic]
else
require_frontend
etopic = case @shell_escape
when :unix
Tools.shell_escape(topic)
when :windows
Tools.win_shell_escape(topic)
else
topic
end
cmd = @frontend % etopic
##p "cmd", cmd
content = `#{cmd} 2>&1`
##p "content", content
# NOTES:
# * Windows' ri always returns 0 even if article is not found. Work around it with a hack.
# * Unix's ri sometimes returns 0 when it offers suggestions. Try `ri Object#is_ax?`.
@cache[topic] = if $?.exitstatus != 0 or content.lines.count < 4
nil
else
content
end
end
end
protected
def require_frontend
raise "`frontend` is not set" if not @frontend
end
end # Library
end # ORI
| mit |
meedan/pender | app/models/concerns/media_html_preprocessor.rb | 939 | module MediaHtmlPreprocessor
extend ActiveSupport::Concern
def preprocess_html(html)
html = find_sharethefacts_links(html) if include_sharethefacts_js(html)
unless html.blank?
html.gsub!('<!-- <div', '<div')
html.gsub!('div> -->', 'div>')
end
html
end
def include_sharethefacts_js(html)
parsed_html = Nokogiri::HTML html
parsed_html.css("script").select { |s| s.attr('src') && s.attr('src').match('sharethefacts')}.any?
end
def find_sharethefacts_links(html)
link = html.match(/<a href=".*sharethefacts.co\/share\/([0-9a-zA-Z\-]+)".*<\/a>/)
return html if link.nil?
uuid = link[1]
sharethefacts_replace_element(html, link, uuid)
end
def sharethefacts_replace_element(html, link, uuid)
source = "https://dhpikd1t89arn.cloudfront.net/html-#{uuid}.html"
content = open(source).read
content = "<div>#{content}</div>"
html.gsub(link[0], content)
end
end
| mit |
DXCanas/content-curation | contentcuration/search/viewsets/savedsearch.py | 1663 | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import IsAuthenticated
from rest_framework.serializers import PrimaryKeyRelatedField
from search.models import SavedSearch
from contentcuration.models import User
from contentcuration.viewsets.base import BulkListSerializer
from contentcuration.viewsets.base import BulkModelSerializer
from contentcuration.viewsets.base import ValuesViewset
class SavedSearchSerializer(BulkModelSerializer):
saved_by = PrimaryKeyRelatedField(queryset=User.objects.all())
def create(self, validated_data):
if "request" in self.context:
user_id = self.context["request"].user.id
# Save under current user
validated_data["saved_by_id"] = user_id
return super().create(validated_data)
class Meta:
model = SavedSearch
fields = (
"id",
"name",
"created",
"modified",
"params",
"saved_by",
)
read_only_fields = ("id",)
list_serializer_class = BulkListSerializer
class SavedSearchViewSet(ValuesViewset):
queryset = SavedSearch.objects.all()
serializer_class = SavedSearchSerializer
permission_classes = [IsAuthenticated]
filter_backends = (DjangoFilterBackend,)
values = (
"id",
"name",
"created",
"modified",
"params",
"saved_by",
)
def get_queryset(self):
user_id = not self.request.user.is_anonymous() and self.request.user.id
return SavedSearch.objects.filter(saved_by_id=user_id).distinct().order_by('-created')
| mit |
bit-foundation/bit-framework | src/Universal/Bit.Universal.OData/Extensions/IFluentClientExtensions.cs | 5855 | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace Simple.OData.Client
{
public static class IFluentClientExtensions
{
public static Task<T> CreateEntryAsync<T>(this IBoundClient<T> client, bool resultRequired, CancellationToken cancellationToken)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.InsertEntryAsync(resultRequired, cancellationToken);
}
public static Task<T> CreateEntryAsync<T>(this IBoundClient<T> client)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.InsertEntryAsync();
}
public static Task<T> CreateEntryAsync<T>(this IBoundClient<T> client, CancellationToken cancellationToken)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.InsertEntryAsync(cancellationToken);
}
public static Task<T> CreateEntryAsync<T>(this IBoundClient<T> client, bool resultRequired)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.InsertEntryAsync(resultRequired);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, ODataExpandOptions includeOptions, Expression<Func<T, object?>> expression)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expandOptions: includeOptions, expression: expression);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, Expression<Func<T, object?>> expression)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expression: expression);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, IEnumerable<string> associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, ODataExpandOptions includeOptions, IEnumerable<string> associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expandOptions: includeOptions, associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, params string[] associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, ODataExpandOptions includeOptions, params string[] associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expandOptions: includeOptions, associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, params ODataExpression[] associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, ODataExpandOptions includeOptions, params ODataExpression[] associations)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expandOptions: includeOptions, associations: associations);
}
public static IBoundClient<T> Include<T>(this IBoundClient<T> client, ODataExpandOptions includeOptions)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Expand(expandOptions: includeOptions);
}
public static IBoundClient<T> Take<T>(this IBoundClient<T> client, int count)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Top(count: count);
}
public static IBoundClient<T> Where<T>(this IBoundClient<T> client, string where)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Filter(filter: where);
}
public static IBoundClient<T> Where<T>(this IBoundClient<T> client, Expression<Func<T, bool>> expression)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Filter(expression: expression);
}
public static IBoundClient<T> Where<T>(this IBoundClient<T> client, ODataExpression expression)
where T : class
{
if (client == null)
throw new ArgumentNullException(nameof(client));
return client.Filter(expression: expression);
}
}
}
| mit |
chris-dickson/neighbourhoods | server/modules/rest/neighbourhoods.js | 3052 | var connectionPool = require('../db/connection');
var UUID = require('../util/uuid');
var Process = require('../util/process_each');
var TABLE_NAME = 'neighbourhoods';
var getAll = function(success,error) {
connectionPool.open(function(conn) {
function onError(err) {
connectionPool.close(conn);
if (error) error(err);
}
function onSuccess(rows) {
connectionPool.close(conn);
success(rows);
}
conn.query('SELECT * FROM ' + TABLE_NAME +' ORDER BY name ASC;', function(err, rows, fields) {
if (err) {
onError(err);
} else {
onSuccess(rows);
}
});
});
};
var add = function(placeMap,success,error) {
connectionPool.open(function(conn) {
function onError(err) {
connectionPool.close(conn);
if (error) error(err);
}
function onSuccess() {
success();
}
// Create a list of queries that insert points 1000 at a time
var queriesList = [];
var statementCount = 0;
var queryBase = 'INSERT INTO ' + TABLE_NAME + ' (id,name,lat,lng,searchString) VALUES';
var query = queryBase;
Object.keys(placeMap).forEach(function(place) {
if (!place || place == '' || place == ' ') {
return;
}
var id = UUID.generate();
var name = place.trim();
var searchString = name;
var lat = placeMap[place].lat;
var lng = placeMap[place].lng;
query += '(' + conn.escape(id) + ',' + conn.escape(name) + ',' + lat + ',' + lng + ',' + conn.escape(searchString) + '),';
statementCount++;
if (statementCount % 1000 === 0) {
query = query.substring(0,queries.length-1);
queriesList.push(query);
query = queryBase;
}
});
query = query.substring(0,query.length-1);
queriesList.push(query);
function onComplete() {
success();
}
function onError(err) {
Process.cancel(PID);
connectionPool.close(conn);
if (error) error(err);
}
// Execute all queries and notify when they've all completed
var PID = Process.each(queriesList,function(query,processNext) {
conn.query(query, function(err,row,fields) {
if (err) onError(err);
processNext();
});
},onComplete);
});
};
var deletePlace = function(id,success,error) {
connectionPool.open(function(conn) {
function onError(err) {
connectionPool.close(conn);
if (error) error(err);
}
function onSuccess(rows) {
connectionPool.close(conn);
success(rows);
}
conn.query('DELETE FROM ' + TABLE_NAME +' WHERE id=' + conn.escape(id), function(err) {
if (err) {
onError(err);
} else {
onSuccess();
}
});
});
};
var addPlace = function(name,lat,lng,success,error) {
var map = {};
map[name] = {
lat : lat,
lng : lng
};
add(map,success,error);
};
module.exports.TABLE_NAME = TABLE_NAME;
module.exports.getAll = getAll;
module.exports.add = add;
module.exports.addPlace = addPlace;
module.exports.deletePlace = deletePlace; | mit |
sansicoin/sansicoin | share/qt/clean_mac_info_plist.py | 899 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Sansicoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Sansicoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.write(newFileContent);
print "Info.plist fresh created"
| mit |
rstancioiu/uva-online-judge | Volume001/151 - Power Crisis/151.cpp | 1097 | //Author Stancioiu Nicu Razvan
//Problem: uva.onlinejudge.org/external/1/151.html
//Description: brute force algorithm
#include <iostream>
#define N 128
using namespace std;
// array of regions turned on or off
int turn[N];
int main()
{
bool problem;
// n the number of regions
// m is the searched 'random' number
// turned is the number of regions that are
// still turned on
int n,m,turned;
while(cin>>n && n!=0)
{
// we search for the first 'random' number m that
// makes the region 13 the last region selected
for(int i=1;;++i)
{
for(int j=1;j<=n;++j)
{
turn[j]=0;
}
turn[1]=1;
int k=0;
int p=2;
turned=n-1;
// the algorithm will continue till we find the region 13
// that's when problem becomes true
problem=false;
while(turned!=0 && !problem)
{
if(p==n+1)
p=1;
if(!turn[p])
{
k++;
if(k==i)
{
turn[p]=1;
k=0;
turned--;
if(p==13)
problem=true;
}
}
p++;
}
if(problem && turned==0)
{
m=i;
break;
}
}
cout<<m<<endl;
}
return 0;
} | mit |
wpscanteam/CMSScanner | lib/cms_scanner/target/server/generic.rb | 2149 | # frozen_string_literal: true
module CMSScanner
class Target < WebSite
module Server
# Generic Server methods
module Generic
# @param [ String ] path
# @param [ Hash ] params The request params
#
# @return [ Symbol ] The detected remote server (:Apache, :IIS, :Nginx)
def server(path = nil, params = {})
headers = headers(path, params)
return unless headers
case headers[:server]
when /\Aapache/i
:Apache
when /\AMicrosoft-IIS/i
:IIS
when /\Anginx/
:Nginx
end
end
# @param [ String ] path
# @param [ Hash ] params The request params
#
# @return [ Hash ] The headers
def headers(path = nil, params = {})
# The HEAD method might be rejected by some servers ... maybe switch to GET ?
NS::Browser.head(url(path), params).headers
end
# @param [ String ] path
# @param [ Hash ] params The request params
#
# @return [ Boolean ] true if url(path) has the directory
# listing enabled, false otherwise
def directory_listing?(path = nil, params = {})
res = NS::Browser.get(url(path), params)
res.code == 200 && res.body.include?('<h1>Index of')
end
# @param [ String ] path
# @param [ Hash ] params The request params
# @param [ String ] selector
# @param [ Regexp ] ignore
#
# @return [ Array<String> ] The first level of directories/files listed,
# or an empty array if none
def directory_listing_entries(path = nil, params = {}, selector = 'pre a', ignore = /parent directory/i)
return [] unless directory_listing?(path, params)
found = []
NS::Browser.get(url(path), params).html.css(selector).each do |node|
entry = node.text.to_s
next if entry&.match?(ignore)
found << entry
end
found
end
end
end
end
end
| mit |
philcrissman/algae | lib/algae/quicksort.rb | 837 | module Algae
class Quicksort
attr_accessor :list, :last
def initialize list
@list = list.dup
@last = list.size-1
end
def sort(start=0,finish=last)
return if start >= finish # return if only one element
pivot = @list[start]
lo, hi = start, finish
while true
while @list[hi] >= pivot
hi -= 1
break if hi <= lo
end
if hi <= lo
@list[lo] = pivot
break
end
@list[lo] = @list[hi]
lo += 1
while @list[lo] < pivot
lo += 1
break if lo >= hi
end
if lo >= hi
lo = hi
@list[hi] = pivot
break
end
@list[hi] = @list[lo]
end
sort(start,lo - 1)
sort(lo + 1, finish)
@list
end
end
end
| mit |
v-yarotsky/TorrentsPub | lib/scrape/authentication_proxy.rb | 451 | require 'delegate'
module Scrape
class AuthenticationProxy < SimpleDelegator
class LoginError < RuntimeError
def message
"Login failed. Check credentials (or maybe refreshing too often?)"
end
end
abstract_method :login
abstract_method :logout
private
def method_missing(m, *args, &block)
debug_message "Authenticating #{m}"
login
super
ensure
logout
end
end
end
| mit |
gmp26/mgc | templates/test/templateSpec.js | 1663 | /*
* sample unit testing for sample templates and implementations
*/
describe('mgcTemplate', function () {
// declare these up here to be global to all tests
var $rootScope, $compile;
beforeEach(module('mgc.directives'));
beforeEach(module('mgc.filters'));
// inject in angular constructs. Injector knows about leading/trailing underscores and does the right thing
// otherwise, you would need to inject these into each test
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
// reset the mgc.config after each test
afterEach(function () {
angular.module('mgc.config').value('mgc.config', {});
});
// optional grouping of tests
describe('filter', function () {
// we're doing filter tests so globally define here for this subset of tests
var $filter;
beforeEach(inject(function (_$filter_) {
$filter = _$filter_;
}));
// very simple boilerplate setup of test for a custom filter
var tmpl;
beforeEach(function () {
tmpl = $filter('filterTmpl');
});
it('should exist when provided', function () {
expect(tmpl).toBeDefined();
});
it('should return exactly what interesting thing the filter is doing to input', function () {
expect(tmpl('text')).toEqual('text');
});
});
// optional grouping of tests
describe('directive', function () {
var element;
it('should create an element if using element-style', function () {
element = $compile('<mgc-directive-tmpl ng-model="a"></mgc-directive-tmpl>')($rootScope);
expect(element).toBeDefined();
});
});
});
| mit |
mogemimi/pomdog | pomdog/gpu/gl4/format_helper.cpp | 951 | // Copyright mogemimi. Distributed under the MIT license.
#include "pomdog/gpu/gl4/format_helper.h"
#include "pomdog/basic/unreachable.h"
#include "pomdog/gpu/comparison_function.h"
namespace pomdog::gpu::detail::gl4 {
GLenum ToComparisonFunctionGL4NonTypesafe(ComparisonFunction comparison) noexcept
{
switch (comparison) {
case ComparisonFunction::Always:
return GL_ALWAYS;
case ComparisonFunction::Equal:
return GL_EQUAL;
case ComparisonFunction::Greater:
return GL_GREATER;
case ComparisonFunction::GreaterEqual:
return GL_GEQUAL;
case ComparisonFunction::Less:
return GL_LESS;
case ComparisonFunction::LessEqual:
return GL_LEQUAL;
case ComparisonFunction::Never:
return GL_NEVER;
case ComparisonFunction::NotEqual:
return GL_NOTEQUAL;
}
POMDOG_UNREACHABLE("Unsupported comparison function");
}
} // namespace pomdog::gpu::detail::gl4
| mit |
liamnoone/saves | lib/saves/cli.rb | 1944 | require 'thor'
module Saves
class CLI < Thor
desc "list", "List all games being backed up"
def list
say("List of Games:", :bold)
GameList.from_config.each do |game|
puts game.name
end
end
desc "backup", "Create a new backup"
def backup(game_name = nil)
game_name ? backup_game(game_name) : backup_all
end
no_commands do
def couldnt_find_game!(game_name)
say "Couldn't find the game '", nil, false
say game_name, :bold, false
say "'. Quitting"
abort
end
def run_backup!(game)
backup = Backup.new(game)
say "Running backup for #{game.name}..."
begin
backup.execute
rescue => exception
say "An error occurred when running the backup"
say exception.message
if ENV['VERBOSE']
say exception.backtrace
end
end
say "Successfully created new backup for "
say game.name, :bold
end
# Run a backup for a single game
def backup_game(game_name)
games = GameList.from_config
game = games.find_game(game_name)
couldnt_find_game!(game_name) unless game
run_backup!(game)
end
def backup_all
games = GameList.from_config
games.each { |game| run_backup!(game) }
end
def list_backups_for_game(game)
say "Backups for the game "
say "#{game.name}:", :bold
backups_for_game = game.backups
backups_for_game.each do |backup|
say "File: "; say(backup, :bold)
backup_stats = game.stats_of_backup(backup)
say "Created: "; say(backup_stats.atime, :bold, true)
end
say # Empty line
end
end
desc "backups", "List all the backups"
def backups
GameList.from_config.each do |game|
list_backups_for_game(game)
end
end
end
end
| mit |
tsingson/learning-react-flux-es6 | test/ItemToggle.react.js | 677 | import React , { Component } from 'react';
export var ItemToggle extends Component {
constructor( props ) {
super( props );
this.onClick = this.onClick.bind(this);
}
onClick(type) {
var item;
switch (type) {
case 'A':
item = "Item A";
break;
case 'B':
item = "Item B";
break;
default:
throw new Error('Unimplemented type');
}
this.props.setActiveItem(item);
}
render () {
return (
<div>Select an Item:
<ul>
<li onClick={this.onClick.bind(this, 'A')}>Item A
<li onClick={this.onClick.bind(this, 'B')}>Item B
</ul>
</div>
);
}
}
| mit |
sdl/groupsharekit.net | Sdl.Community.GroupShareKit/Models/Response/TranslationMemory/ParagraphUnit.cs | 1745 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sdl.Community.GroupShareKit.Models.Response.TranslationMemory
{
public class ParagraphUnit
{
/// <summary>
/// Gets or sets the id
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets parent file id
/// </summary>
public string ParentFileId { get; set; }
/// <summary>
/// Gets or sets if is structure
/// </summary>
public bool IsStructure { get; set; }
/// <summary>
/// Gets or sets if is locked
/// </summary>
public bool IsLocked { get; set; }
/// <summary>
/// Gets or sets structure context id
/// </summary>
public int StructureContextId { get; set; }
/// <summary>
/// Gets or sets list of context list
/// </summary>
public List<int> ContextList { get; set; }
/// <summary>
/// Gets or sets index
/// </summary>
public int Index { get; set; }
/// <summary>
/// Gets or sets source language details
/// </summary>
public ParagraphUnitLanguageDetails Source { get; set; }
/// <summary>
/// Gets or sets target language details
/// </summary>
public ParagraphUnitLanguageDetails Target { get; set; }
/// <summary>
/// Gets or sets comment definition ids
/// </summary>
public List<int> CommentDefinitionIds { get; set; }
/// <summary>
/// Gets or sets metadata
/// </summary>
public Metadata Metadata { get; set; }
}
}
| mit |
mhdehghan/SamanGar | src/samanGar/normalizer/Normalizer.java | 2465 | package samanGar.normalizer;
import samanGar.ReadData;
import samanGar.sentence.Sentence;
import samanGar.sentence.Word;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by dehghan on 8/24/2017.
*/
public class Normalizer {
Map<Character, Character> charSet;
List<Character> validCharSet;
public Normalizer() {
charSet=new ReadData().readMap("resources/normalizer/replaceChars.txt");
validCharSet=new ReadData().readChars("resources/normalizer/validChars.txt");
}
public Normalizer(String charSetFile,String validCharFile) {
charSet = new ReadData().readMap(charSetFile);
validCharSet=new ReadData().readChars(validCharFile);
}
private void replaceCharSet(Sentence sentence) {
for (int i = 0; i < sentence.length(); i++) {
StringBuilder result = new StringBuilder();
String tmp = sentence.get(i);
for (int j = 0; j < tmp.length(); j++) {
if (charSet.containsKey(tmp.charAt(j))) {
result.append(charSet.get(tmp.charAt(j)));
} else {
result.append(tmp.charAt(j));
}
}
sentence.replaceWord(i, result.toString());
}
}
private void invalidChar(Sentence sentence) {
for (int i = 0; i < sentence.length(); i++) {
StringBuilder result = new StringBuilder();
String tmp = sentence.get(i);
for (int j = 0; j < tmp.length(); j++) {
if (validCharSet.contains(tmp.charAt(j))) {
result.append(tmp.charAt(j));
} else {
//Do nothing!
}
}
sentence.replaceWord(i, result.toString());
}
}
private void removeEmptyWords(Sentence sentence)
{
for (int i = 0; i < sentence.length(); i++) {
if (sentence.get(i).trim().equals(""))
{sentence.remove(i);i--;}
}
}
public void process(Sentence sentence) {
replaceCharSet(sentence);
invalidChar(sentence);
//pullRegex(sentence);
//splitPunctuation(sentence);
//Add semi-space here!
//new SemiSpace().process(sentence);
removeEmptyWords(sentence);
//pushRegex(sentence);
}
}
| mit |
viennashe/viennashe-dev | viennashe/simulator_quantity.hpp | 11565 | #ifndef VIENNASHE_SIMULATOR_QUANTITY_HPP
#define VIENNASHE_SIMULATOR_QUANTITY_HPP
/* ============================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaSHE - The Vienna Spherical Harmonics Expansion Boltzmann Solver
-----------------
http://viennashe.sourceforge.net/
License: MIT (X11), see file LICENSE in the base directory
=============================================================================== */
/** @file viennashe/simulator_quantity.hpp
@brief Defines a generic simulator quantity for use within the solvers of ViennaSHE
*/
#include <vector>
#include <string>
#include "viennagrid/mesh/mesh.hpp"
#include "viennashe/forwards.h"
namespace viennashe
{
/** @brief Holds a function per quantity, which returns the name of the respective quantity as std::string. */
namespace quantity
{
inline std::string potential() { return "Electrostatic potential"; }
inline std::string electron_density() { return "Electron density"; }
inline std::string hole_density() { return "Hole density"; }
inline std::string density_gradient_electron_correction() { return "DG electron correction potential"; }
inline std::string density_gradient_hole_correction() { return "DG hole correction potential"; }
inline std::string lattice_temperature() { return "Lattice temperature"; }
inline std::string electron_distribution_function() { return "Electron distribution function"; }
inline std::string hole_distribution_function() { return "Hole distribution function"; }
}
/** @brief Common representation of any quantity associated with objects of a certain type.
*
* This is the minimum requirement one can have: Return value for a vertex/cell.
*/
template<typename AssociatedT, typename ValueT = double>
class const_quantity
{
public:
typedef const_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
typedef associated_type access_type;
const_quantity(std::string quan_name,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name),
values_(num_values, default_value) {}
const_quantity(std::string quan_name,
std::vector<ValueT> const & values_array)
: name_(quan_name),
values_(values_array) {}
const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { }
void operator=(self_type const & o) { name_(o.name_); values_(o.values_); }
ValueT get_value (associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
std::string name() const { return name_; }
private:
std::string name_;
std::vector<ValueT> values_;
};
template<typename AssociatedT, typename ValueT = double>
class non_const_quantity
{
public:
typedef non_const_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
non_const_quantity(std::string quan_name,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name), values_(num_values, default_value) {}
non_const_quantity(std::string quan_name,
std::vector<ValueT> const & values_array)
: name_(quan_name), values_(values_array) {}
non_const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { }
void operator=(self_type const & o) { name_(o.name_); values_(o.values_); }
ValueT get_value(associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
void set_value(associated_type const & elem, ValueT value) { values_.at(static_cast<std::size_t>(elem.id().get())) = value; }
std::string name() const { return name_; }
private:
std::string name_;
std::vector<ValueT> values_;
};
template <typename ValueT = double>
struct robin_boundary_coefficients
{
ValueT alpha;
ValueT beta;
};
template<typename AssociatedT, typename ValueT = double>
class unknown_quantity
{
std::size_t get_id(AssociatedT const & elem) const { return static_cast<std::size_t>(elem.id().get()); }
public:
typedef unknown_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
typedef robin_boundary_coefficients<ValueT> robin_boundary_type;
unknown_quantity() {} // to fulfill default constructible concept!
unknown_quantity(std::string const & quan_name,
equation_id quan_equation,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name),
equation_(quan_equation),
values_ (num_values, default_value),
boundary_types_ (num_values, BOUNDARY_NONE),
boundary_values_ (num_values, default_value),
boundary_values_alpha_ (num_values, 0),
defined_but_unknown_mask_(num_values, false),
unknowns_indices_ (num_values, -1),
log_damping_(false)
{}
unknown_quantity(self_type const & o)
: name_(o.name_),
equation_(o.equation_),
values_ (o.values_),
boundary_types_ (o.boundary_types_),
boundary_values_ (o.boundary_values_),
boundary_values_alpha_ (o.boundary_values_alpha_),
defined_but_unknown_mask_(o.defined_but_unknown_mask_),
unknowns_indices_ (o.unknowns_indices_),
log_damping_ (o.log_damping_)
{ }
void operator=(self_type const & o)
{
name_ = o.name_;
equation_ = o.equation_;
values_ = o.values_;
boundary_types_ = o.boundary_types_;
boundary_values_ = o.boundary_values_;
boundary_values_alpha_ = o.boundary_values_alpha_;
defined_but_unknown_mask_= o.defined_but_unknown_mask_;
unknowns_indices_ = o.unknowns_indices_;
log_damping_ = o.log_damping_;
}
std::string get_name() const { return name_; }
equation_id get_equation() const { return equation_; }
ValueT get_value(associated_type const & elem) const { return values_.at(get_id(elem)); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
void set_value(associated_type const & elem, ValueT value) { values_.at(get_id(elem)) = value; }
void set_value(associated_type const & elem, robin_boundary_type value) { (void)elem; (void)value; } //TODO: Fix this rather ugly hack which stems from set_boundary_for_material()
// Dirichlet and Neumann
ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(get_id(elem)); }
void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(get_id(elem)) = value; }
// Robin boundary conditions
/** @brief Returns the coefficients alpha and beta for the Robin boundary condition du/dn = beta - alpha u
*
*
* @return A pair holding (beta, alpha). .first returns beta, .second returns alpha
*/
robin_boundary_type get_boundary_values(associated_type const & elem) const
{
robin_boundary_type ret;
ret.alpha = boundary_values_alpha_.at(get_id(elem));
ret.beta = boundary_values_.at(get_id(elem));
return ret;
}
/** @brief Setter function for Robin boundary conditions.
*
* Note that this is an overload rather than a new function 'set_boundary_values' in order to have a uniform setter interface.
*/
void set_boundary_value(associated_type const & elem, robin_boundary_type const & values)
{
boundary_values_.at(get_id(elem)) = values.beta;
boundary_values_alpha_.at(get_id(elem)) = values.alpha;
}
boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(get_id(elem)); }
void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(get_id(elem)) = value; }
bool get_unknown_mask(associated_type const & elem) const { return defined_but_unknown_mask_.at(get_id(elem)); }
void set_unknown_mask(associated_type const & elem, bool value) { defined_but_unknown_mask_.at(get_id(elem)) = value; }
long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(get_id(elem)); }
void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(get_id(elem)) = value; }
std::size_t get_unknown_num() const
{
std::size_t num = 0;
for (std::size_t i=0; i<unknowns_indices_.size(); ++i)
{
if (unknowns_indices_[i] >= 0)
++num;
}
return num;
}
// possible design flaws:
std::vector<ValueT> const & values() const { return values_; }
std::vector<boundary_type_id> const & boundary_types() const { return boundary_types_; }
std::vector<ValueT> const & boundary_values() const { return boundary_values_; }
std::vector<bool> const & defined_but_unknown_mask() const { return defined_but_unknown_mask_; }
std::vector<long> const & unknowns_indices() const { return unknowns_indices_; }
bool get_logarithmic_damping() const { return log_damping_; }
void set_logarithmic_damping(bool b) { log_damping_ = b; }
private:
std::string name_;
equation_id equation_;
std::vector<ValueT> values_;
std::vector<boundary_type_id> boundary_types_;
std::vector<ValueT> boundary_values_;
std::vector<ValueT> boundary_values_alpha_;
std::vector<bool> defined_but_unknown_mask_;
std::vector<long> unknowns_indices_;
bool log_damping_;
};
} //namespace viennashe
#endif
| mit |
henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Post/Syncs/History/Responses/Json/Reader/SyncHistoryRemovePostResponseNotFoundGroupObjectJsonReader.cs | 3548 | namespace TraktApiSharp.Objects.Post.Syncs.History.Responses.Json.Reader
{
using Newtonsoft.Json;
using Objects.Json;
using Post.Responses.Json.Reader;
using System.Threading;
using System.Threading.Tasks;
internal class SyncHistoryRemovePostResponseNotFoundGroupObjectJsonReader : AObjectJsonReader<ITraktSyncHistoryRemovePostResponseNotFoundGroup>
{
public override async Task<ITraktSyncHistoryRemovePostResponseNotFoundGroup> ReadObjectAsync(JsonTextReader jsonReader, CancellationToken cancellationToken = default)
{
if (jsonReader == null)
return await Task.FromResult(default(ITraktSyncHistoryRemovePostResponseNotFoundGroup));
if (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.StartObject)
{
var notFoundMoviesReader = new PostResponseNotFoundMovieArrayJsonReader();
var notFoundShowsReader = new PostResponseNotFoundShowArrayJsonReader();
var notFoundSeasonsReader = new PostResponseNotFoundSeasonArrayJsonReader();
var notFoundEpisodesReader = new PostResponseNotFoundEpisodeArrayJsonReader();
ITraktSyncHistoryRemovePostResponseNotFoundGroup syncHistoryRemovePostResponseNotFoundGroup = new TraktSyncHistoryRemovePostResponseNotFoundGroup();
while (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.PropertyName)
{
var propertyName = jsonReader.Value.ToString();
switch (propertyName)
{
case JsonProperties.SYNC_POST_RESPONSE_NOT_FOUND_GROUP_PROPERTY_NAME_MOVIES:
syncHistoryRemovePostResponseNotFoundGroup.Movies = await notFoundMoviesReader.ReadArrayAsync(jsonReader, cancellationToken);
break;
case JsonProperties.SYNC_POST_RESPONSE_NOT_FOUND_GROUP_PROPERTY_NAME_SHOWS:
syncHistoryRemovePostResponseNotFoundGroup.Shows = await notFoundShowsReader.ReadArrayAsync(jsonReader, cancellationToken);
break;
case JsonProperties.SYNC_POST_RESPONSE_NOT_FOUND_GROUP_PROPERTY_NAME_SEASONS:
syncHistoryRemovePostResponseNotFoundGroup.Seasons = await notFoundSeasonsReader.ReadArrayAsync(jsonReader, cancellationToken);
break;
case JsonProperties.SYNC_POST_RESPONSE_NOT_FOUND_GROUP_PROPERTY_NAME_EPISODES:
syncHistoryRemovePostResponseNotFoundGroup.Episodes = await notFoundEpisodesReader.ReadArrayAsync(jsonReader, cancellationToken);
break;
case JsonProperties.SYNC_HISTORY_REMOVE_POST_RESPONSE_NOT_FOUND_GROUP_PROPERTY_NAME_IDS:
syncHistoryRemovePostResponseNotFoundGroup.HistoryIds = await JsonReaderHelper.ReadUnsignedLongArrayAsync(jsonReader, cancellationToken);
break;
default:
await JsonReaderHelper.ReadAndIgnoreInvalidContentAsync(jsonReader, cancellationToken);
break;
}
}
return syncHistoryRemovePostResponseNotFoundGroup;
}
return await Task.FromResult(default(ITraktSyncHistoryRemovePostResponseNotFoundGroup));
}
}
}
| mit |
gively/mdex_client | lib/mdex_client/mdata/record.rb | 1416 | require 'mdex_client/mdata/node'
module MDEXClient
module MData
class Record < Node
class Attributes < Hash
def initialize(*args)
super(*args)
@dimension_value_ids = {}
@dimension_ids = {}
end
def dimension_value_id(key)
@dimension_value_ids[key]
end
def dimension_id(key)
@dimension_ids[key]
end
def dimension_keys
@dimension_ids.keys
end
def property_keys
keys - dimension_keys
end
def <<(node)
key = node["Key"]
self[key] = node.text
if node.name == "AssignedDimensionValue"
@dimension_value_ids[key] = node["Id"]
@dimension_ids[key] = node["DimensionId"]
end
end
end
attr_accessor :id, :attributes, :snippets
def initialize(element_or_hash=nil)
@attributes = Attributes.new
super(element_or_hash)
end
def initialize_from_element!
@id = @element["Id"]
xpath("mdata:Attributes/mdata:AssignedDimensionValue | mdata:Attributes/mdata:Property").each do |attribute|
@attributes << attribute
end
@snippets = property_list("mdata:Snippets/mdata:Snippet")
end
end
end
end
| mit |
Kunstmaan/BootstrapCK4-Skin | plugins/div/lang/sr-latn.js | 722 | /*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'sr-latn', {
IdInputLabel: 'Id',
advisoryTitleInputLabel: 'Advisory naslov',
cssClassInputLabel: 'Stylesheet klase',
edit: 'Edit Div', // MISSING
inlineStyleInputLabel: 'Inline Style', // MISSING
langDirLTRLabel: 'S leva na desno (LTR)',
langDirLabel: 'Smer jezika',
langDirRTLLabel: 'S desna na levo (RTL)',
languageCodeInputLabel: ' Language Code', // MISSING
remove: 'Remove Div', // MISSING
styleSelectLabel: 'Stil',
title: 'Create Div Container', // MISSING
toolbar: 'Create Div Container' // MISSING
} );
| mit |
ConnorWiseman/koa-hbs-renderer | lib/template-manager.js | 3495 | /**
* @file Exports a function that creates a set of functions for managing
* compiled and cached templates.
*/
const fs = require('fs');
const getPaths = require('./get-paths.js');
/**
* Obtains the current timestamp in seconds.
* @return {Number}
* @private
*/
function timestamp() {
return Math.floor(Date.now() / 1000);
};
/**
* Creates and manages an in-memory cache of compiled Handlebars template
* functions, returning an object with two methods for interacting with the
* cache and file system.
* @param {Object} options
* @return {Object}
*/
module.exports = function templateManager(options) {
/**
* An in-memory cache of compiled Handlebars template functions.
* @type {Object}
* @public
*/
let cache = {
layout: {},
partial: {},
view: {}
};
// Alias certain options for brevity
const env = options.environment;
const expires = options.cacheExpires;
const ext = options.extension;
const hbs = options.hbs;
/**
* Compiles and caches the template stored at the specified file path, if it
* exists. Cached templates will be stored in the in-memory cache belonging
* to the specified template type.
* @param {String} baseDir The base directory of the templates
* @param {String} filePath The path of the template to compile
* @param {String} type The type of template this is
* @return {Promise.<Function>}
* @public
*/
function compileTemplate(baseDir, filePath, type) {
return new options.Promise((resolve, reject) => {
let now = timestamp();
let name = filePath.substring(baseDir.length + 1).replace(/\\/g, '/');
name = name.substring(0, name.indexOf('.'));
// A cached template is only invalidated if the environment is something
// other than `development` and the time-to-live has been exceeded.
if (cache[type][name] &&
(env !== 'development' || cache[type][name]._cached + expires > now)) {
return resolve(cache[type][name]);
}
fs.readFile(filePath, 'utf-8', (error, contents) => {
if (error) {
return reject(error);
}
cache[type][name] = hbs.compile(contents.trim());
// Decorate the cached function with private members. The underscore
// is necessary to avoid conflict with function's name to prevent all
// compiled templates from being named `ret` in the cache.
cache[type][name]._name = name;
cache[type][name]._cached = timestamp();
return resolve(cache[type][name]);
});
});
};
/**
* Compiles and caches all the templates in the specified directory, if it
* exists. Returns a Promise for an object map of compiled Handlebars template
* functions, mapped from the results of compileTemplate above.
* @param {String} dir The directory to search in
* @param {String} type The type of templates these are
* @return {Promise.<Object>}
* @public
*/
function compileTemplates(dir, type) {
return getPaths(dir, ext, options).then(paths => {
return options.Promise.all(paths.map(filePath => {
return compileTemplate(dir, filePath, type);
})).then(templates => {
return templates.reduce((all, current) => {
all[current._name] = current;
return all;
}, {});
});
});
};
// The cache is exposed for ease of testing.
return { cache, compileTemplate, compileTemplates };
};
| mit |
opengovernment/person-widget | tests/acceptance/thanks-test.js | 704 | import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
var application;
module('Acceptance: Thanks', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('when process is finished, user is thanked', function(assert) {
visit('/');
click('.start');
fillIn('input.email-input', 'test_user@example.com');
click('input[type="submit"]');
andThen(function() {
var copy = "Thank you! We'll deliver this question publicly and ask\n Bernard Sanders to respond. We'll be in touch by email.";
assert.equal(find('.copy').text(), copy);
});
});
| mit |
cmkeene/Reddit-Project | Reddit_Application/app/src/main/java/com/spencerkerber/reddit_application/PostsFragment.java | 4122 | package com.spencerkerber.reddit_application;
/**
* Created by spencerkerber on 11/15/15.
*/
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* While this looks like a lot of code, all this class
* actually does is load the posts in to the listview.
*/
public class PostsFragment extends Fragment{
ListView postsList;
ArrayAdapter<Post> adapter;
Handler handler;
String subreddit;
List<Post> posts;
PostsHolder postsHolder;
PostsFragment(){
handler=new Handler();
posts=new ArrayList<Post>();
}
public static Fragment newInstance(String subreddit){
PostsFragment pf=new PostsFragment();
pf.subreddit=subreddit;
pf.postsHolder=new PostsHolder(pf.subreddit);
return pf;
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.posts
, container
, false);
postsList=(ListView)v.findViewById(R.id.posts_list);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
}
private void initialize(){
// This should run only once for the fragment as the
// setRetainInstance(true) method has been called on
// this fragment
if(posts.size()==0){
// Must execute network tasks outside the UI
// thread. So create a new thread.
new Thread(){
public void run(){
posts.addAll(postsHolder.fetchPosts());
// UI elements should be accessed only in
// the primary thread, so we must use the
// handler here.
handler.post(new Runnable(){
public void run(){
createAdapter();
}
});
}
}.start();
}else{
createAdapter();
}
}
/**
* This method creates the adapter from the list of posts
* , and assigns it to the list.
*/
private void createAdapter(){
// Make sure this fragment is still a part of the activity.
if(getActivity()==null) return;
adapter=new ArrayAdapter<Post>(getActivity()
,R.layout.post_item
, posts){
@Override
public View getView(int position,
View convertView,
ViewGroup parent) {
if(convertView==null){
convertView=getActivity()
.getLayoutInflater()
.inflate(R.layout.post_item, null);
}
TextView postTitle;
postTitle=(TextView)convertView
.findViewById(R.id.post_title);
TextView postDetails;
postDetails=(TextView)convertView
.findViewById(R.id.post_details);
TextView postScore;
postScore=(TextView)convertView
.findViewById(R.id.post_score);
postTitle.setText(posts.get(position).title);
postDetails.setText(posts.get(position).getDetails());
postScore.setText(posts.get(position).getScore());
return convertView;
}
};
postsList.setAdapter(adapter);
}
} | mit |
nuandy/othello | apps/mongo/app/controllers/Auth.java | 6125 | package mongo.app.controllers;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.*;
import com.google.gson.Gson;
import src.main.othello.web.controller.impl.AbstractControllerImpl;
import com.mongodb.util.JSON;
import mongo.app.models.User;
import mongo.app.models.UserOid;
import mongo.app.models.MongoDB;
import mongo.app.models.Util;
public class Auth extends AbstractControllerImpl {
private static Logger logger = Logger.getLogger(Auth.class);
public void doMain(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (request.getParameter("route").equals("login")) {
this.login(request, response);
} else if (request.getParameter("route").equals("register")) {
this.register(request, response);
} else if (request.getParameter("route").equals("logout")) {
this.logout(request, response);
}
}
public Boolean allowed(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String cookieValue = Util.getCookieValue(request.getCookies(), "myapptoken", "");
List<Object> results = new ArrayList<Object>();
MongoDB.connect();
MongoDB.getCollection("user");
Map query = new HashMap();
query.put("auth_token", cookieValue);
results = MongoDB.getDocuments(query);
if (!results.isEmpty()) {
String result = JSON.serialize(results.get(0));
Gson gson = new Gson();
User user = gson.fromJson(result, User.class);
if (user.getAuthToken() != null) {
return true;
}
}
return false;
}
public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String email = request.getParameter("email");
String password = request.getParameter("password");
if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(password)) {
List<Object> results = new ArrayList<Object>();
MongoDB.connect();
MongoDB.getCollection("user");
Map query = new HashMap();
query.put("email", email);
query.put("password", password);
results = MongoDB.getDocuments(query);
if (!results.isEmpty()) {
String result = JSON.serialize(results.get(0));
Gson gson = new Gson();
User user = gson.fromJson(result, User.class);
if (StringUtils.isNotBlank(user.getId())) {
this.setUserCookie(user, request, response);
response.sendRedirect("success.jsp");
}
} else {
request.setAttribute("failed", true);
super.forward("app/views/login.jsp", request, response);
}
} else {
request.setAttribute("failed", true);
super.forward("app/views/login.jsp", request, response);
}
}
public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String email = request.getParameter("email");
String fullname = request.getParameter("fullname");
String password = request.getParameter("password");
if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(fullname) && StringUtils.isNotBlank(password)) {
if (Util.validateEmail(email) == true && password.length() > 7) {
List<String> indexNames = new ArrayList<String>();
indexNames.add("email");
indexNames.add("fullname");
Map document = new HashMap();
document.put("email", email);
document.put("fullname", fullname);
document.put("status", 1);
document.put("password", password);
MongoDB.connect();
MongoDB.getCollection("user");
MongoDB.setIndex(indexNames);
MongoDB.setDocument(document);
request.setAttribute("registered", true);
super.forward("app/views/login.jsp", request, response);
} else if (Util.validateEmail(email) == false) {
request.setAttribute("bad_email", true);
super.forward("app/views/register.jsp", request, response);
} else if (password.length() < 8) {
request.setAttribute("bad_password", true);
super.forward("app/views/register.jsp", request, response);
} else {
request.setAttribute("failed", true);
super.forward("app/views/register.jsp", request, response);
}
} else {
request.setAttribute("failed", true);
super.forward("app/views/register.jsp", request, response);
}
}
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Cookie userCookie = new Cookie("myapptoken", "");
userCookie.setMaxAge(0);
response.addCookie(userCookie);
request.setAttribute("signedout", true);
super.forward("app/views/login.jsp", request, response);
}
public static void setUserCookie(User user, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String data = Util.encryptCookie(user);
Cookie userCookie = new Cookie("myapptoken", data);
userCookie.setMaxAge(3600);
response.addCookie(userCookie);
Map document = new HashMap();
document.put("status", user.getStatus());
document.put("fullname", user.getName());
document.put("email", user.getEmail());
document.put("password", user.getPassword());
document.put("created_at", user.getCreatedAt());
document.put("auth_token", data);
MongoDB.connect();
MongoDB.getCollection("user");
MongoDB.updateDocumentByEmail(user.getEmail(), document);
}
}
| mit |
nomcopter/generator-typescript-react | generators/app/templates/src/_index.ts | 52 | export const PACKAGE_NAME = '<%= kebabCaseName %>';
| mit |
rsanchez/Deep | tests/functional/UploadPrefRepositoryTest.php | 661 | <?php
use rsanchez\Deep\Model\UploadPref;
use rsanchez\Deep\Repository\UploadPrefRepository;
class UploadPrefRepositoryTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->repository = new UploadPrefRepository(new UploadPref());
}
public function testFind()
{
$uploadPref = $this->repository->find(1);
$this->assertInstanceOf('\\rsanchez\\Deep\\Model\\UploadPref', $uploadPref);
}
public function testGetUploadPrefs()
{
$query = $this->repository->getUploadPrefs();
$this->assertInstanceOf('\\rsanchez\\Deep\\Collection\\UploadPrefCollection', $query);
}
}
| mit |
mywei1989/blog | models/user.js | 2393 | var settings = require('../settings/settings.js');
var MongoClient = require('./db.js');
function User(user){
this.userName = user.userName;
this.userPassword = user.userPassword;
this.sessionID = user.sessionID
}
User.prototype.login = function(callback){
var that = this;
var user = {
userName:this.userName,
userPassword:this.userPassword
};
MongoClient.connect(settings.mongoUrl,function(err,db){
if(!err){
var collection = db.collection('users');
collection.findOne({userName:user.userName,userPassword:user.userPassword},function(err,result){
if((!err)&&result){
callback&&callback(true);
}else{
callback&&callback(false);
}
db.close();
});
}else{
return callback&&callback(err);
}
});
};
User.prototype.saveCookie = function(callback){
var user = {
sessionID:this.sessionID
};
MongoClient.connect(settings.mongoUrl,function(err,db){
if(!err){
var collection = db.collection('usercookie');
collection.insert({
sessionID:user.sessionID
},function(err,result){
if((!err)&&result){
callback&&callback(true);
}else{
callback&&callback(false);
}
db.close();
});
}else{
return callback&&callback(err);
}
});
};
User.prototype.checkLogin = function(callback){
var that = this;
var user = {
sessionID:this.sessionID
};
MongoClient.connect(settings.mongoUrl,function(err,db){
if(!err){
var collection = db.collection('usercookie');
collection.findOne({sessionID:user.sessionID},function(err,usercookieinfo){
db.close();
if((!err)&&usercookieinfo){
callback(null,usercookieinfo);
}else{
callback&&callback(err);
}
});
}else{
return callback&&callback(err);
}
});
};
User.prototype.register = function(callback){
var user = {
userName:this.userName,
userPassword:this.userPassword
};
MongoClient.connect(settings.mongoUrl,function(err,db){
if(!err){
var collection = db.collection('users');
collection.insert({
userName:user.userName,
userPassword:user.userPassword
},function(err,result){
db.close();
});
}else{
return callback&&callback(err);
}
});
};
module.exports = User; | mit |
lucaslencinas/react-node-socketio-template | src/components/Layout/Layout.js | 643 | import React from 'react';
import PropTypes from 'prop-types';
import styles from './Layout.css';
const Layout = ({
alert,
children,
onCloseAlert
}) => (
<div className={styles.layout}>
<div display-if={alert} className={styles.alert}>
<div className={styles.alertMessage}>
{alert.message}
</div>
<div className={styles.alertClose} onClick={onCloseAlert}>
X
</div>
</div>
<div className={styles.content}>
{children}
</div>
</div>
);
Layout.propTypes = {
alert: PropTypes.object,
children: PropTypes.object,
onCloseAlert: PropTypes.func
};
export default Layout;
| mit |
softjourn-internship/sales-if-ua | src/main/java/sales/admission/domain/Admission.java | 1882 | package sales.admission.domain;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import sales.users.domain.User;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Myroslav on 14.08.2015.
*/
@Entity
@Table(name = "Admission")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE)
public class Admission {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty("id")
private int id;
@ManyToOne(targetEntity = User.class)
@JoinColumn(name = "shop", referencedColumnName = "id")
@JsonIgnore
private User shop;
@Column(name = "sum")
@JsonProperty("sum")
private double sum;
@Column(name = "paymentId")
@JsonProperty("paymentId")
private String paymentId;
@Column(name = "date")
@JsonProperty("date")
private Date date;
@PrePersist
private void onCreateAdmissionInstance() {
date = new Date();
}
public Admission() {
}
public Admission(User shop, double sum, String paymentId) {
this.shop = shop;
this.sum = sum;
this.paymentId = paymentId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getShop() {
return shop;
}
public void setShop(User shop) {
this.shop = shop;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
| mit |
jwiesel/sfdcCommander | sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/ActionOverride.java | 10480 | /**
* ActionOverride.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap._2006._04.metadata;
public class ActionOverride implements java.io.Serializable {
private java.lang.String actionName;
private java.lang.String comment;
private java.lang.String content;
private com.sforce.soap._2006._04.metadata.FormFactor formFactor;
private java.lang.Boolean skipRecordTypeSelect;
private com.sforce.soap._2006._04.metadata.ActionOverrideType type;
public ActionOverride() {
}
public ActionOverride(
java.lang.String actionName,
java.lang.String comment,
java.lang.String content,
com.sforce.soap._2006._04.metadata.FormFactor formFactor,
java.lang.Boolean skipRecordTypeSelect,
com.sforce.soap._2006._04.metadata.ActionOverrideType type) {
this.actionName = actionName;
this.comment = comment;
this.content = content;
this.formFactor = formFactor;
this.skipRecordTypeSelect = skipRecordTypeSelect;
this.type = type;
}
/**
* Gets the actionName value for this ActionOverride.
*
* @return actionName
*/
public java.lang.String getActionName() {
return actionName;
}
/**
* Sets the actionName value for this ActionOverride.
*
* @param actionName
*/
public void setActionName(java.lang.String actionName) {
this.actionName = actionName;
}
/**
* Gets the comment value for this ActionOverride.
*
* @return comment
*/
public java.lang.String getComment() {
return comment;
}
/**
* Sets the comment value for this ActionOverride.
*
* @param comment
*/
public void setComment(java.lang.String comment) {
this.comment = comment;
}
/**
* Gets the content value for this ActionOverride.
*
* @return content
*/
public java.lang.String getContent() {
return content;
}
/**
* Sets the content value for this ActionOverride.
*
* @param content
*/
public void setContent(java.lang.String content) {
this.content = content;
}
/**
* Gets the formFactor value for this ActionOverride.
*
* @return formFactor
*/
public com.sforce.soap._2006._04.metadata.FormFactor getFormFactor() {
return formFactor;
}
/**
* Sets the formFactor value for this ActionOverride.
*
* @param formFactor
*/
public void setFormFactor(com.sforce.soap._2006._04.metadata.FormFactor formFactor) {
this.formFactor = formFactor;
}
/**
* Gets the skipRecordTypeSelect value for this ActionOverride.
*
* @return skipRecordTypeSelect
*/
public java.lang.Boolean getSkipRecordTypeSelect() {
return skipRecordTypeSelect;
}
/**
* Sets the skipRecordTypeSelect value for this ActionOverride.
*
* @param skipRecordTypeSelect
*/
public void setSkipRecordTypeSelect(java.lang.Boolean skipRecordTypeSelect) {
this.skipRecordTypeSelect = skipRecordTypeSelect;
}
/**
* Gets the type value for this ActionOverride.
*
* @return type
*/
public com.sforce.soap._2006._04.metadata.ActionOverrideType getType() {
return type;
}
/**
* Sets the type value for this ActionOverride.
*
* @param type
*/
public void setType(com.sforce.soap._2006._04.metadata.ActionOverrideType type) {
this.type = type;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ActionOverride)) return false;
ActionOverride other = (ActionOverride) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.actionName==null && other.getActionName()==null) ||
(this.actionName!=null &&
this.actionName.equals(other.getActionName()))) &&
((this.comment==null && other.getComment()==null) ||
(this.comment!=null &&
this.comment.equals(other.getComment()))) &&
((this.content==null && other.getContent()==null) ||
(this.content!=null &&
this.content.equals(other.getContent()))) &&
((this.formFactor==null && other.getFormFactor()==null) ||
(this.formFactor!=null &&
this.formFactor.equals(other.getFormFactor()))) &&
((this.skipRecordTypeSelect==null && other.getSkipRecordTypeSelect()==null) ||
(this.skipRecordTypeSelect!=null &&
this.skipRecordTypeSelect.equals(other.getSkipRecordTypeSelect()))) &&
((this.type==null && other.getType()==null) ||
(this.type!=null &&
this.type.equals(other.getType())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getActionName() != null) {
_hashCode += getActionName().hashCode();
}
if (getComment() != null) {
_hashCode += getComment().hashCode();
}
if (getContent() != null) {
_hashCode += getContent().hashCode();
}
if (getFormFactor() != null) {
_hashCode += getFormFactor().hashCode();
}
if (getSkipRecordTypeSelect() != null) {
_hashCode += getSkipRecordTypeSelect().hashCode();
}
if (getType() != null) {
_hashCode += getType().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ActionOverride.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ActionOverride"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("actionName");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "actionName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("comment");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "comment"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("content");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "content"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("formFactor");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "formFactor"));
elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "FormFactor"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("skipRecordTypeSelect");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "skipRecordTypeSelect"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("type");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ActionOverrideType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| mit |
camillescott/boink | include/goetia/hashing/canonical.hh | 13385 | /**
* (c) Camille Scott, 2019
* File : canonical.hh
* License: MIT
* Author : Camille Scott <camille.scott.w@gmail.com>
* Date : 08.01.2020
*/
#ifndef GOETIA_CANONICAL_HH
#define GOETIA_CANONICAL_HH
#include <cstdint>
#include <iostream>
#include <limits>
namespace goetia::hashing {
inline constexpr bool DIR_LEFT = false;
inline constexpr bool DIR_RIGHT = true;
/**
* @Synopsis Default model for a regular, single-value hash.
* Generally, just a thin wrapper for uint64_t
* which provides a common interface exposing
* the underlying value through value().
*
* @tparam ValueType Underlying storage type.
*/
template<class ValueType = uint64_t>
struct Hash {
typedef ValueType value_type;
value_type hash;
Hash(const value_type hash)
: hash(hash)
{
}
Hash()
: hash(std::numeric_limits<value_type>::max())
{
}
Hash(const Hash& other)
: hash(other.hash)
{
}
const value_type value() const {
return hash;
}
operator value_type() const {
return value();
}
__attribute__((visibility("default")))
friend bool operator>(const Hash& lhs, const Hash& rhs) {
return lhs.value() > rhs.value();
}
__attribute__((visibility("default")))
friend bool operator<(const Hash& lhs, const Hash& rhs) {
return lhs.value() < rhs.value();
}
__attribute__((visibility("default")))
friend bool operator==(const Hash& lhs, const Hash& rhs) {
return lhs.value() == rhs.value();
}
};
template<class ValueType>
__attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os, const Hash<ValueType>& _this) {
os << "<Hash h=" << _this.value()
<< ">";
return os;
}
/**
* @Synopsis Model for a canonical k-mer. Stores two value_type
* as fw and rc hashes; value() provides the canonical
* hash. Matches Hash interface.
*
* @tparam ValueType
*/
template<class ValueType = uint64_t>
struct Canonical {
typedef ValueType value_type;
value_type fw_hash, rc_hash;
Canonical()
: fw_hash(std::numeric_limits<value_type>::max()),
rc_hash(std::numeric_limits<value_type>::max())
{
}
Canonical(const value_type fw,
const value_type rc)
: fw_hash(fw),
rc_hash(rc)
{
}
Canonical(const Canonical& other)
: fw_hash(other.fw_hash),
rc_hash(other.rc_hash)
{
}
const bool sign() const {
return fw_hash < rc_hash ? true : false;
}
const value_type value() const {
return fw_hash < rc_hash ? fw_hash : rc_hash;
}
operator value_type() const {
return value();
}
__attribute__((visibility("default")))
friend bool operator>(const Canonical& lhs, const Canonical& rhs) {
return lhs.value() > rhs.value();
}
__attribute__((visibility("default")))
friend bool operator<(const Canonical& lhs, const Canonical& rhs) {
return lhs.value() < rhs.value();
}
__attribute__((visibility("default")))
friend bool operator==(const Canonical& lhs, const Canonical& rhs) {
return lhs.value() == rhs.value();
}
};
template<class ValueType> __attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os, const Canonical<ValueType>& _this) {
os << "<Canonical"
<< " fw=" << _this.fw_hash
<< " rc=" << _this.rc_hash
<< " sign=" << _this.sign()
<< ">";
return os;
}
/**
* @Synopsis Helper struct so we can write, for example,
* Wmer<Hash<uint64_t>, Unikmer>
* instead of
* Wmer<Hash, uint64_t, Unikmer>
* which makes later composition more general and
* safer.
*
* @tparam T
* @tparam MinimizerType
*/
template<class T, class MinimizerType>
struct Wmer;
/**
* @Synopsis A Hash with an associated minimizer.
*
*/
template<template<class> class HashType, class ValueType,
class MinimizerType>
struct Wmer<HashType<ValueType>, MinimizerType> {
typedef HashType<ValueType> hash_type;
typedef ValueType value_type;
typedef MinimizerType minimizer_type;
hash_type hash;
minimizer_type minimizer;
Wmer(const hash_type& hash,
const minimizer_type& minimizer)
: hash(hash),
minimizer(minimizer)
{
}
Wmer()
: hash(),
minimizer()
{
}
Wmer(const Wmer& other)
: hash(other.hash),
minimizer(other.minimizer)
{
}
const value_type value() const {
return hash.value();
}
operator value_type() const {
return hash.value();
}
operator hash_type() const {
return hash;
}
__attribute__((visibility("default")))
friend bool operator>(const Wmer& lhs, const Wmer& rhs) {
return lhs.hash > rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator<(const Wmer& lhs, const Wmer& rhs) {
return lhs.hash < rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator==(const Wmer& lhs, const Wmer& rhs) {
return lhs.hash == rhs.hash;
}
};
template<template<class> class HashType, class ValueType,
class MinimizerType>
__attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os,
const Wmer<HashType<ValueType>, MinimizerType>& wmer) {
os << "<Wmer"
<< " hash=" << wmer.hash
<< " minimizer=" << wmer.minimizer
<< ">";
return os;
}
template<typename T>
struct Kmer;
/**
* @Synopsis Models a Kmer: a Hash and its string repr. The hash_type
* must comform to the Hash template interface.
*
* NOTE: The variadic Extras parameter is need so that Kmer
* can accept a Wmer as its HashType (or for that matter,
* anything that comforms to Hash but takes extra
* template parameters). Naturally, Extras can also just
* be empty, in which case it matches regular Hash<uint64_t>
* etc.
*/
template<template<class, class...> class HashType, class ValueType, class...Extras>
struct Kmer<HashType<ValueType, Extras...>> {
typedef HashType<ValueType, Extras...> hash_type;
typedef typename hash_type::value_type value_type;
hash_type hash;
std::string kmer;
Kmer(const hash_type& hash,
const std::string& kmer)
: hash(hash),
kmer(kmer)
{
}
Kmer()
: hash(),
kmer(0, ' ')
{
}
Kmer(const Kmer& other)
: hash(other.hash),
kmer(other.kmer)
{
}
const value_type value() const {
return hash.value();
}
operator value_type() const {
return hash.value();
}
operator hash_type() const {
return hash;
}
__attribute__((visibility("default")))
friend bool operator>(const Kmer& lhs, const Kmer& rhs) {
return lhs.hash > rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator<(const Kmer& lhs, const Kmer& rhs) {
return lhs.hash < rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator==(const Kmer& lhs, const Kmer& rhs) {
return lhs.hash == rhs.hash;
}
};
template<template<class, class...> class HashType, class ValueType,
class...Extras>
__attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os, const Kmer<HashType<ValueType, Extras...>>& kmer) {
os << "<Kmer"
<< " hash=" << kmer.hash
<< " kmer=" << kmer.kmer
<< ">";
return os;
}
/**
* @Synopsis helper struct so we can write, for example,
* Shift<Hash<uint64_t>, DIR_LEFT>
* instead of
* Shift<Hash, uint64_t, DIR_LEFT>
* which makes later composition more general and
* safer. See specialization below.
*
* @tparam T
* @tparam Direction
*/
template <class T, bool Direction>
struct Shift;
/**
* @Synopsis Models a directional shift; conforms to Hash
* and provides the direction and extension symbol.
*
*/
template <template<class, class...> class HashType, class ValueType, class... Extras,
bool Direction>
struct Shift<HashType<ValueType, Extras...>, Direction> {
typedef HashType<ValueType, Extras...> hash_type;
typedef typename hash_type::value_type value_type;
static const bool direction = Direction;
hash_type hash;
char symbol;
Shift(const hash_type hash,
const char symbol)
: hash(hash),
symbol(symbol)
{
}
Shift()
: hash(),
symbol('\0')
{
}
Shift(const Shift& other)
: Shift(other.hash, other.symbol)
{
}
const value_type value() const {
return hash.value();
}
operator value_type() const {
return hash.value();
}
operator hash_type() const {
return hash;
}
__attribute__((visibility("default")))
friend bool operator>(const Shift& lhs, const Shift& rhs) {
return lhs.hash > rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator<(const Shift& lhs, const Shift& rhs) {
return lhs.hash < rhs.hash;
}
__attribute__((visibility("default")))
friend bool operator==(const Shift& lhs, const Shift& rhs) {
return lhs.hash == rhs.hash;
}
};
template <template<class, class...> class HashType, class ValueType, class... Extras,
bool Direction>
__attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os,
const Shift<HashType<ValueType, Extras...>, Direction>& shift) {
os << "<Shift"
<< " hash=" << shift.hash
<< " symbol=" << shift.symbol
<< " direction=" << shift.direction
<< ">";
return os;
}
/**
* @Synopsis Models any value with an associated partition ID.
*
* @tparam ValueType
*/
template <class ValueType>
struct Partitioned {
typedef ValueType value_type;
value_type v;
uint64_t partition;
Partitioned(const value_type& v,
const uint64_t partition)
: v(v),
partition(partition)
{
}
Partitioned()
: v(),
partition(std::numeric_limits<uint64_t>::max())
{
}
Partitioned(const Partitioned& other)
: v(other.v),
partition(other.partition)
{
}
const value_type value() const {
return v;
}
__attribute__((visibility("default")))
friend bool operator>(const Partitioned& lhs, const Partitioned& rhs) {
return lhs.v > rhs.v;
}
__attribute__((visibility("default")))
friend bool operator<(const Partitioned& lhs, const Partitioned& rhs) {
return lhs.v < rhs.v;
}
__attribute__((visibility("default")))
friend bool operator==(const Partitioned& lhs, const Partitioned& rhs) {
return lhs.v == rhs.v;
}
};
template <class ValueType>
__attribute__((visibility("default")))
inline std::ostream&
operator<<(std::ostream& os, const Partitioned<ValueType>& p) {
os << "<Partitioned"
<< " value=" << p.v
<< " partition=" << p.partition
<< ">";
return os;
}
typedef goetia::hashing::Partitioned<goetia::hashing::Hash<>> Unikmer;
typedef goetia::hashing::Partitioned<goetia::hashing::Canonical<>> CanonicalUnikmer;
typedef goetia::hashing::Wmer<goetia::hashing::Hash<>, goetia::hashing::Unikmer> UnikmerWmer;
typedef goetia::hashing::Wmer<goetia::hashing::Canonical<>, goetia::hashing::CanonicalUnikmer> CanonicalUnikmerWmer;
typedef goetia::hashing::Shift<goetia::hashing::Hash<>, goetia::hashing::DIR_LEFT> LeftShift;
typedef goetia::hashing::Shift<goetia::hashing::Hash<>, goetia::hashing::DIR_RIGHT> RightShift;
typedef goetia::hashing::Shift<goetia::hashing::Canonical<>, goetia::hashing::DIR_LEFT> LeftCanonicalShift;
typedef goetia::hashing::Shift<goetia::hashing::Canonical<>, goetia::hashing::DIR_RIGHT> RightCanonicalShift;
}
extern template class goetia::hashing::Hash<uint64_t>;
extern template class goetia::hashing::Canonical<goetia::hashing::Hash<uint64_t>>;
extern template class goetia::hashing::Kmer<goetia::hashing::Hash<uint64_t>>;
extern template class goetia::hashing::Kmer<goetia::hashing::Canonical<uint64_t>>;
extern template class goetia::hashing::Kmer<goetia::hashing::UnikmerWmer>;
extern template class goetia::hashing::Kmer<goetia::hashing::CanonicalUnikmerWmer>;
extern template class goetia::hashing::Wmer<goetia::hashing::Hash<uint64_t>, goetia::hashing::Unikmer>;
extern template class goetia::hashing::Wmer<goetia::hashing::Canonical<uint64_t>, goetia::hashing::CanonicalUnikmer>;
extern template class goetia::hashing::Shift<goetia::hashing::Hash<uint64_t>, goetia::hashing::DIR_LEFT>;
extern template class goetia::hashing::Shift<goetia::hashing::Hash<uint64_t>, goetia::hashing::DIR_RIGHT>;
extern template class goetia::hashing::Shift<goetia::hashing::Canonical<uint64_t>, goetia::hashing::DIR_LEFT>;
extern template class goetia::hashing::Shift<goetia::hashing::Canonical<uint64_t>, goetia::hashing::DIR_RIGHT>;
#endif
| mit |
efalder413/PKMNBreeder | src/AppBundle/Entity/Ability.php | 2565 | <?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Ability
*
* @ORM\Table(name="ability")
* @ORM\Entity(repositoryClass="AppBundle\Repository\AbilityRepository")
*/
class Ability
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=191)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="effect", type="string", length=191)
*/
private $effect;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\AbilityStack", mappedBy="abilityId")
*/
private $abilityStack;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Ability
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set effect
*
* @param string $effect
*
* @return Ability
*/
public function setEffect($effect)
{
$this->effect = $effect;
return $this;
}
/**
* Get effect
*
* @return string
*/
public function getEffect()
{
return $this->effect;
}
/**
* Constructor
* @param string $name
* @param string $effect
*/
public function __construct($name = null, $effect = null)
{
$this->name = $name;
$this->effect = $effect;
$this->abilityStack = new ArrayCollection();
}
/**
* Add abilityStack
*
* @param AbilityStack $abilityStack
*
* @return Ability
*/
public function addAbilityStack(AbilityStack $abilityStack)
{
$this->abilityStack[] = $abilityStack;
return $this;
}
/**
* Remove abilityStack
*
* @param AbilityStack $abilityStack
*/
public function removeAbilityStack(AbilityStack $abilityStack)
{
$this->abilityStack->removeElement($abilityStack);
}
/**
* Get abilityStack
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAbilityStack()
{
return $this->abilityStack;
}
}
| mit |
nherzalla/ProfileX-1 | src/app/app.module.ts | 1577 | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpModule} from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MyDatePickerModule } from 'mydatepicker';
import {routing,appRoutingProviders} from './app.routing';
import { AppComponent } from './app.component';
import { AUTH_PROVIDERS } from 'angular2-jwt';
import {Auth} from './services/auth.service';
import {AuthGuard} from './auth.guard';
import {profileService} from './services/profile.service';
import {HomeComponent} from './components/home/home.component';
import {ProfileComponent} from './components/profile/profile.component';
import {SettingsComponent} from './components/settings/settings.component';
import {AddressComponent} from './components/settings/address.component';
import {EducationComponent} from './components/settings/education.component';
import {ExperienceComponent} from './components/settings/experience.component';
import {PortfolioComponent} from './components/settings/portfolio.component';
@NgModule({
imports: [ BrowserModule,routing,HttpModule,FormsModule,ReactiveFormsModule,MyDatePickerModule],
declarations: [ AppComponent,HomeComponent,ProfileComponent,SettingsComponent,AddressComponent,EducationComponent,ExperienceComponent,PortfolioComponent],
bootstrap: [ AppComponent ],
providers:[
appRoutingProviders,
AUTH_PROVIDERS,
Auth,
AuthGuard,
HttpModule,
profileService
]
})
export class AppModule { }
| mit |
SiiHackathon/BikeTracking | BikeTracker/Entities/User.cs | 339 | namespace BikeTracker.Entities
{
public class User : Entity
{
public override long Id => UserId;
public long UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public long TeamId { get; set; }
public string Image { get; set; }
}
} | mit |
YHTechnology/ProjectManager | ProductManager/ProductManager/ViewModel/ProductManagers/LinkResponsePersonModel.cs | 17013 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Windows.Data.DomainServices;
using ProductManager.ViewData.Entity;
using ProductManager.Web.Service;
using ProductManager.Views.ProductManagers;
namespace ProductManager.ViewModel.ProductManagers
{
public enum LinkType
{
LinkProject,
LinkPerson
}
public class LinkResponsePersonModel : NotifyPropertyChanged
{
public ObservableCollection<ProjectEntity> ProjectEntityList { get; set; }
public ObservableCollection<ProjectEntity> ProjectLinkEntityList { get; set; }
public ObservableCollection<ProjectResponsibleEntity> ProjectResponsibleEntityList { get; set; }
public ObservableCollection<ProjectResponsibleEntity> ProjectResponsibleEntityALLList { get; set; }
public String FilterContext { get; set; }
private ProjectEntity selectProjectEntity;
public ProjectEntity SelectProjectEntity
{
get
{
return selectProjectEntity;
}
set
{
if (selectProjectEntity != value)
{
selectProjectEntity = value;
using (projectResponsibleView.DeferRefresh())
{
projectResponsibleView.MoveToFirstPage();
}
}
}
}
private ProjectEntity selectLinkProjectEntity;
public ProjectEntity SelectLinkProjectEntity
{
get
{
return selectLinkProjectEntity;
}
set
{
if (selectLinkProjectEntity != value)
{
selectLinkProjectEntity = value;
}
}
}
private LinkType linkType = LinkType.LinkProject;
public LinkType LinkTypes
{
get
{
return linkType;
}
set
{
if (linkType != value)
{
linkType = value;
if (linkType == LinkType.LinkProject)
{
IsEnable = false;
}
else if (linkType == LinkType.LinkPerson)
{
IsEnable = true;
}
}
}
}
private bool isEnable = false;
public bool IsEnable
{
get
{
return isEnable;
}
set
{
if (isEnable != value)
{
isEnable = value;
UpdateChanged("IsEnable");
}
}
}
private ProjectResponsibleEntity selectProjectResponsibleEntity;
public ProjectResponsibleEntity SelectProjectResponsibleEntity
{
get
{
return selectProjectResponsibleEntity;
}
set
{
if (selectProjectResponsibleEntity != value)
{
selectProjectResponsibleEntity = value;
}
}
}
public ICommand OnReflash { get; private set; }
public ICommand OnAddToProject { get; private set; }
public ICommand OnRemoveProject { get; private set; }
public ICommand OnOk { get; private set; }
public ICommand OnCancel { get; private set; }
private DomainCollectionView<ProductManager.Web.Model.project> projectView;
private DomainCollectionViewLoader<ProductManager.Web.Model.project> projectLoader;
private EntityList<ProductManager.Web.Model.project> projectSource;
private DomainCollectionView<ProductManager.Web.Model.project_responsible> projectResponsibleView;
private DomainCollectionViewLoader<ProductManager.Web.Model.project_responsible> projectResponsibLoader;
private EntityList<ProductManager.Web.Model.project_responsible> projectResponsibSource;
private Dictionary<int, DepartmentEntity> DepartmentEntityDictionary;
private Dictionary<String, UserEntity> UserEntityDictionary;
private ProductDomainContext ProductDomainContext;
private ChildWindow childWidow;
public LinkResponsePersonModel(ChildWindow aChildWindow
, ProductDomainContext aProductDomainContext
, Dictionary<int, DepartmentEntity> aDepartmentEntityDictionary
, Dictionary<String, UserEntity> aUserEntityDictionary)
{
ProductDomainContext = aProductDomainContext;
childWidow = aChildWindow;
DepartmentEntityDictionary = aDepartmentEntityDictionary;
UserEntityDictionary = aUserEntityDictionary;
ProjectEntityList = new ObservableCollection<ProjectEntity>();
ProjectLinkEntityList = new ObservableCollection<ProjectEntity>();
ProjectResponsibleEntityList = new ObservableCollection<ProjectResponsibleEntity>();
ProjectResponsibleEntityALLList = new ObservableCollection<ProjectResponsibleEntity>();
OnReflash = new DelegateCommand(OnReflashCommand);
OnAddToProject = new DelegateCommand(OnAddToProjectCommand);
OnRemoveProject = new DelegateCommand(OnRemoveProjectCommand);
OnOk = new DelegateCommand(OnOkCommand);
OnCancel = new DelegateCommand(OnCancelCommand);
projectSource = new EntityList<ProductManager.Web.Model.project>(ProductDomainContext.projects);
projectLoader = new DomainCollectionViewLoader<ProductManager.Web.Model.project>(
LoadProjectEntities,
LoadOperationProjectCompleted
);
projectView = new DomainCollectionView<ProductManager.Web.Model.project>(projectLoader, projectSource);
projectResponsibSource = new EntityList<ProductManager.Web.Model.project_responsible>(ProductDomainContext.project_responsibles);
projectResponsibLoader = new DomainCollectionViewLoader<ProductManager.Web.Model.project_responsible>(
LoadProjectResponseEntities,
LoadOperationProjectResponseCompleted
);
projectResponsibleView = new DomainCollectionView<ProductManager.Web.Model.project_responsible>(projectResponsibLoader, projectResponsibSource);
}
public void LoadData()
{
LoadOperation<ProductManager.Web.Model.project_responsible> loadOperationProject =
ProductDomainContext.Load<ProductManager.Web.Model.project_responsible>(ProductDomainContext.GetProject_responsibleQuery());
loadOperationProject.Completed += loadOperationProjectReponse_Completed;
}
private void loadOperationProjectReponse_Completed(Object sender, EventArgs e)
{
ProjectResponsibleEntityALLList.Clear();
LoadOperation loadOperation = sender as LoadOperation;
foreach (ProductManager.Web.Model.project_responsible project_responsible in loadOperation.Entities)
{
ProjectResponsibleEntity projectResponsibleEntity = new ProjectResponsibleEntity();
projectResponsibleEntity.ProjectResponsible = project_responsible;
projectResponsibleEntity.Update();
ProjectResponsibleEntityALLList.Add(projectResponsibleEntity);
}
using (projectView.DeferRefresh())
{
projectView.MoveToFirstPage();
}
}
private LoadOperation<ProductManager.Web.Model.project> LoadProjectEntities()
{
EntityQuery<ProductManager.Web.Model.project> lQuery = ProductDomainContext.GetProjectQuery();
if (FilterContext != null)
{
lQuery = lQuery.Where(c => c.manufacture_number.ToLower().Contains(FilterContext.ToLower()) || c.project_name.ToLower().Contains(FilterContext.ToLower()));
}
return ProductDomainContext.Load(lQuery.SortAndPageBy(this.projectView));
}
private void LoadOperationProjectCompleted(LoadOperation<ProductManager.Web.Model.project> aLoadOperation)
{
ProjectEntityList.Clear();
foreach (ProductManager.Web.Model.project project in aLoadOperation.Entities)
{
ProjectEntity projectEntity = new ProjectEntity();
projectEntity.Project = project;
projectEntity.Update();
ProjectEntityList.Add(projectEntity);
}
}
private LoadOperation<ProductManager.Web.Model.project_responsible> LoadProjectResponseEntities()
{
EntityQuery<ProductManager.Web.Model.project_responsible> lQuery = ProductDomainContext.GetProject_responsibleQuery();
if (SelectProjectEntity != null)
{
lQuery = lQuery.Where(c => c.manufacture_number == SelectProjectEntity.ManufactureNumber);
}
return ProductDomainContext.Load(lQuery.SortAndPageBy(this.projectResponsibleView));
}
private void LoadOperationProjectResponseCompleted(LoadOperation<ProductManager.Web.Model.project_responsible> aLoadOperation)
{
ProjectResponsibleEntityList.Clear();
foreach (ProductManager.Web.Model.project_responsible projectResponsible in aLoadOperation.Entities)
{
ProjectResponsibleEntity projectResponsibleEntity = new ProjectResponsibleEntity();
projectResponsibleEntity.ProjectResponsible = projectResponsible;
projectResponsibleEntity.Update();
DepartmentEntity lDepartmentEntityTemp;
if (DepartmentEntityDictionary.TryGetValue(projectResponsibleEntity.DepartmentID, out lDepartmentEntityTemp))
{
projectResponsibleEntity.DepartmentName = lDepartmentEntityTemp.DepartmentName;
}
if (projectResponsibleEntity.ResponsiblePersionName == null)
{
continue;
}
UserEntity lUserEntityTemp;
if (UserEntityDictionary.TryGetValue(projectResponsibleEntity.ResponsiblePersionName, out lUserEntityTemp))
{
projectResponsibleEntity.UserPhoneNumber = lUserEntityTemp.UserPhoneNumber;
}
ProjectResponsibleEntityList.Add(projectResponsibleEntity);
}
}
void OnReflashCommand()
{
using (projectView.DeferRefresh())
{
projectView.MoveToFirstPage();
}
}
void OnAddToProjectCommand()
{
if (SelectProjectEntity != null)
{
bool lIsAdded = false;
foreach (ProjectEntity projectEntity in ProjectLinkEntityList)
{
if (projectEntity.ManufactureNumber == SelectProjectEntity.ManufactureNumber)
{
lIsAdded = true;
break;
}
}
if (!lIsAdded)
{
ProjectLinkEntityList.Add(selectProjectEntity);
}
}
}
void OnRemoveProjectCommand()
{
if (selectLinkProjectEntity != null)
{
ProjectLinkEntityList.Remove(selectLinkProjectEntity);
}
}
void OnOkCommand()
{
if (linkType == LinkType.LinkProject)
{
foreach (ProjectResponsibleEntity lProjectResponsibleEntity in ProjectResponsibleEntityList)
{
foreach (ProjectEntity lProjectEntity in ProjectLinkEntityList)
{
bool lHasAdd = false;
foreach (ProjectResponsibleEntity lProjectResponsibleEntityCheck in ProjectResponsibleEntityALLList)
{
if (lProjectResponsibleEntityCheck.ManufactureNumber == lProjectEntity.ManufactureNumber
&& lProjectResponsibleEntityCheck.DepartmentID == lProjectResponsibleEntity.DepartmentID
&& lProjectResponsibleEntityCheck.ResponsiblePersionName == lProjectResponsibleEntity.ResponsiblePersionName)
{
lHasAdd = true;
break;
}
}
if (lHasAdd)
{
continue;
}
ProjectResponsibleEntity lProjectResponseibleEntity = new ProjectResponsibleEntity();
lProjectResponseibleEntity.ProjectResponsible = new ProductManager.Web.Model.project_responsible();
lProjectResponseibleEntity.ManufactureNumber = lProjectEntity.ManufactureNumber;
lProjectResponseibleEntity.DepartmentID = lProjectResponsibleEntity.DepartmentID;
lProjectResponseibleEntity.ResponsiblePersionName = lProjectResponsibleEntity.ResponsiblePersionName;
lProjectResponseibleEntity.Descript = lProjectResponsibleEntity.Descript;
lProjectResponseibleEntity.DUpdate();
ProductDomainContext.project_responsibles.Add(lProjectResponseibleEntity.ProjectResponsible);
}
}
}
else if (linkType == LinkType.LinkPerson)
{
if (selectProjectResponsibleEntity != null)
{
LinkResponsePersonWindow lLinkResponsePersonWindow = childWidow as LinkResponsePersonWindow;
foreach (ProjectResponsibleEntity lSProjectResponsibleEntity in lLinkResponsePersonWindow.projectPersonDataGrid.SelectedItems)
{
ProjectResponsibleEntity lProjectResponsibleEntity = lSProjectResponsibleEntity;
foreach (ProjectEntity lProjectEntity in ProjectLinkEntityList)
{
bool lHasAdd = false;
foreach (ProjectResponsibleEntity lProjectResponsibleEntityCheck in ProjectResponsibleEntityALLList)
{
if (lProjectResponsibleEntityCheck.ManufactureNumber == lProjectEntity.ManufactureNumber
&& lProjectResponsibleEntityCheck.DepartmentID == lProjectResponsibleEntity.DepartmentID
&& lProjectResponsibleEntityCheck.ResponsiblePersionName == lProjectResponsibleEntity.ResponsiblePersionName)
{
lHasAdd = true;
break;
}
}
if (lHasAdd)
{
continue;
}
ProjectResponsibleEntity lProjectResponseibleEntity = new ProjectResponsibleEntity();
lProjectResponseibleEntity.ProjectResponsible = new ProductManager.Web.Model.project_responsible();
lProjectResponseibleEntity.ManufactureNumber = lProjectEntity.ManufactureNumber;
lProjectResponseibleEntity.DepartmentID = lProjectResponsibleEntity.DepartmentID;
lProjectResponseibleEntity.ResponsiblePersionName = lProjectResponsibleEntity.ResponsiblePersionName;
lProjectResponseibleEntity.Descript = lProjectResponsibleEntity.Descript;
lProjectResponseibleEntity.DUpdate();
ProductDomainContext.project_responsibles.Add(lProjectResponseibleEntity.ProjectResponsible);
}
}
}
}
childWidow.DialogResult = true;
}
void OnCancelCommand()
{
childWidow.DialogResult = false;
}
}
}
| mit |
xapple/seqsearch | seqsearch/databases/pr_two.py | 2945 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair.
MIT Licensed.
Contact at www.sinclair.bio
"""
# Built-in modules #
import os
# First party modules #
from seqsearch.databases import Database
from autopaths.auto_paths import AutoPaths
from autopaths.file_path import FilePath
# Third party modules #
# Constants #
home = os.environ.get('HOME', '~') + '/'
###############################################################################
class PrTwo(Database):
"""
This is the PR2 database.
https://figshare.com/articles/PR2_rRNA_gene_database/3803709
To install:
from seqsearch.databases.pr_two import pr_two
pr_two.download()
pr_two.unzip()
print pr_two.tax_depth_freq
It will put it in ~/databases/pr_two_11/
"""
base_url = "https://ndownloader.figshare.com/articles/3803709/versions/"
short_name = "pr_two"
long_name = 'Protist Ribosomal Reference database (PR2) - SSU rRNA gene database'
all_paths = """
/archive.zip
/pr2_gb203_version_4.5.zip
/pr2_gb203_version_4.5.fasta
/pr2_gb203_version_4.5.taxo
"""
@property
def rank_names(self):
"""The names of the ranks. Total 9 ranks."""
return ['Domain', # 0
'Kingdom', # 1
'Phylum', # 2
'Class', # 3
'Order', # 4
'Family', # 5
'Tribe', # 6
'Genus', # 7
'Species'] # 8
def __init__(self, version, base_dir=None):
# Attributes #
self.version = version
self.short_name = self.short_name + "_" + self.version
# Base directory #
if base_dir is None: base_dir = home
self.base_dir = base_dir + 'databases/' + self.short_name + '/'
self.p = AutoPaths(self.base_dir, self.all_paths)
# URL #
self.url = self.base_url + self.version
# The archive #
self.dest = self.p.archive
# The results #
self.alignment = FilePath(self.base_dir + "pr_two.gb203_v%s.align" % self.version)
self.taxonomy = FilePath(self.base_dir + "pr_two.gb203_v%s.tax" % self.version)
# The part that mothur will use for naming files #
self.nickname = "gb203_v%s" % self.version
def download(self):
self.dest.directory.create(safe=True)
self.dest.remove()
print("\nDownloading", self.url)
import wget
wget.download(self.url, out=self.dest.path)
def unzip(self):
self.dest.unzip_to(self.base_dir, single=False)
self.p.archive_zip.unzip_to(self.base_dir, single=False)
self.p.pr2_zip.unzip_to(self.base_dir, single=False)
self.p.fasta.move_to(self.alignment)
self.p.taxo.move_to(self.taxonomy)
###############################################################################
pr_two = PrTwo("11") | mit |
nazar/MediaCMS | app/helpers/markers_helper.rb | 179 | module MarkersHelper
def draw_map(obj, options)
width = options.delete(:width); width ||= '100%'
height = options.delete(:height); height ||= '100%'
end
end
| mit |
T-Alex/Common | src/TAlex.Common/Helpers/ConvertEx.cs | 1681 | using System;
using System.Text;
namespace TAlex.Common.Helpers
{
/// <summary>
/// Represents the extended methods for converting data types, such as bytes to string.
/// </summary>
public static class ConvertEx
{
#region Fields
private const long BytesInKilobyte = 1024L;
private const long BytesInMegabyte = 1048576L;
private const long BytesInGigabyte = 1073741824L;
private const long BytesInTerabyte = 1099511627776L;
#endregion
#region Methods
/// <summary>
/// Converts the number of bytes to display string.
/// </summary>
/// <param name="bytes">A <see cref="System.Int64"/> represents the number of bytes for converting.</param>
/// <returns>string converting from bytes.</returns>
public static string BytesToDisplayString(long bytes)
{
if (bytes < BytesInKilobyte)
return String.Format("{0} bytes", bytes);
else if (bytes < BytesInMegabyte)
return String.Format("{0} KB", Round2Digits((double)bytes / BytesInKilobyte));
else if (bytes < BytesInGigabyte)
return String.Format("{0} MB", Round2Digits((double)bytes / BytesInMegabyte));
else if (bytes < BytesInTerabyte)
return String.Format("{0} GB", Round2Digits((double)bytes / BytesInGigabyte));
else
return String.Format("{0} TB", Round2Digits((double)bytes / BytesInTerabyte));
}
private static double Round2Digits(double value)
{
return Math.Round(value, 2);
}
#endregion
}
}
| mit |
PPMESSAGE/ppcom-android-sdk | PPMessageSDK/sdk/src/main/java/com/ppmessage/sdk/core/model/UnackedMessagesLoader.java | 10154 | package com.ppmessage.sdk.core.model;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.ppmessage.sdk.core.L;
import com.ppmessage.sdk.core.PPMessageSDK;
import com.ppmessage.sdk.core.api.OnAPIRequestCompleted;
import com.ppmessage.sdk.core.bean.common.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Help you load all unacked messages
*
* Created by ppmessage on 5/19/16.
*/
public class UnackedMessagesLoader {
private static final String TAG = UnackedMessagesLoader.class.getSimpleName();
public static final String LOG_API_PAGE_UNACKED_MESSAGES_EMPTY = "[" + TAG + "]: call api to page unacked messages, empty result, cancel request";
public static final String LOG_PROCESS_UNACKED_MESSAGES_COMPLETED = "[" + TAG + "]: process %d unacked messages completed, total unacked messages count %d";
private static final int DEFAULT_PAGE_UNACKED_MESSAGES_COUNT = 30;
private PPMessageSDK messageSDK;
private UnackedMessagesProcessor messagesProcessor;
private boolean stop;
public UnackedMessagesLoader(PPMessageSDK messageSDK) {
this.messageSDK = messageSDK;
this.stop = false;
}
/**
*
* Get all unacked messages, and send them to {@link com.ppmessage.sdk.core.notification.INotification},
* so, make it seems like this messages are arrived by ws channel, not by api channel
*
*/
public void loadUnackedMessages() {
final JSONObject requestParam = getRequestParam();
if (requestParam == null) return;
messageSDK.getAPI().pageUnackedMessages(requestParam, new OnAPIRequestCompleted() {
@Override
public void onResponse(JSONObject jsonResponse) {
List<String> unackedMessageJSONStringList = UnackedMessagesLoader.this.onResponse(jsonResponse);
if (unackedMessageJSONStringList == null || unackedMessageJSONStringList.isEmpty()) {
L.d(LOG_API_PAGE_UNACKED_MESSAGES_EMPTY);
return;
}
UnackedMessagesLoader.this.stopLastMessagesProcessor();
messagesProcessor = new UnackedMessagesProcessor(messageSDK, unackedMessageJSONStringList);
messagesProcessor.setCompletedCallback(new UnackedMessagesProcessor.OnCompletedCallback() {
@Override
public void onCompleted(int messageProcessedCount, int messageTotalCount) {
L.d(LOG_PROCESS_UNACKED_MESSAGES_COMPLETED, messageProcessedCount, messageTotalCount);
if (!isStop()) {
loadUnackedMessages();
}
}
});
messagesProcessor.start();
}
@Override
public void onCancelled() {
}
@Override
public void onError(int errorCode) {
}
});
}
public void stop() {
stopLastMessagesProcessor();
stop = true;
}
public boolean inLoading() {
return messagesProcessor != null && !messagesProcessor.isCompleted() && !isStop();
}
public boolean isStop() {
return stop;
}
private void stopLastMessagesProcessor() {
if (messagesProcessor != null) {
messagesProcessor.stop();
messagesProcessor = null;
}
}
private JSONObject getRequestParam() {
final User activeUser = messageSDK.getNotification().getConfig().getActiveUser();
final String appUUID = messageSDK.getNotification().getConfig().getAppUUID();
if (activeUser == null || appUUID == null) return null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("page_offset", 0);
jsonObject.put("page_size", DEFAULT_PAGE_UNACKED_MESSAGES_COUNT);
jsonObject.put("app_uuid", appUUID);
jsonObject.put("user_uuid", activeUser.getUuid());
} catch (JSONException e) {
L.e(e);
}
return jsonObject;
}
// {
// "error_string":"success.",
// "list":[
// "589e0bc2-1d93-11e6-9523-acbc327f19e9"
// ],
// "uri":"/GET_UNACKED_MESSAGES",
// "message":{
// "589e0bc2-1d93-11e6-9523-acbc327f19e9":"{\"ci\": \"88c2b34a-1ce2-11e6-b80a-acbc327f19e9\", \"ft\": \"DU\", \"tt\": \"AP\", \"bo\": \"123\", \"ts\": 1463642936.526738, \"mt\": \"NOTI\", \"tl\": null, \"ms\": \"TEXT\", \"ti\": \"c56adc0a-1b54-11e6-bc9f-acbc327f19e9\", \"fi\": \"c5657363-1b54-11e6-aaea-acbc327f19e9\", \"id\": \"e43c6a0a-4d92-49fa-f83d-5c367a4d6150\", \"ct\": \"S2P\"}"
// },
// "error_code":0,
// "size":1
// }
private List<String> onResponse(JSONObject jsonResponse) {
try {
if (jsonResponse.getInt("error_code") != 0) {
return null;
}
JSONArray jsonArray = jsonResponse.getJSONArray("list");
JSONObject messageDictionary = jsonResponse.getJSONObject("message");
List<String> unackedMessages = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
String pid = jsonArray.getString(i);
String message = messageDictionary.has(pid) ? messageDictionary.getString(pid) : null;
String messageWithPid = convertMessageToWSMessageStyle(message, pid);
if (messageWithPid != null) {
unackedMessages.add(messageWithPid);
}
}
return unackedMessages;
} catch (JSONException e) {
L.e(e);
}
return null;
}
// Add pid to message:
//
//"{\"ci\": \"88c2b34a-1ce2-11e6-b80a-acbc327f19e9\", \"ft\": \"DU\", \"tt\": \"AP\", \"bo\": \"123\", \"ts\": 1463642936.526738, \"mt\": \"NOTI\", \"tl\": null, \"ms\": \"TEXT\", \"ti\": \"c56adc0a-1b54-11e6-bc9f-acbc327f19e9\", \"fi\": \"c5657363-1b54-11e6-aaea-acbc327f19e9\", \"id\": \"e43c6a0a-4d92-49fa-f83d-5c367a4d6150\", \"ct\": \"S2P\"}"
//
//
private String convertMessageToWSMessageStyle(String message, String pid) {
try {
JSONObject msgWrapper = new JSONObject();
JSONObject jsonObject = new JSONObject(message);
jsonObject.put("pid", pid);
msgWrapper.put("type", "MSG");
msgWrapper.put("msg", jsonObject);
return msgWrapper.toString();
} catch (JSONException e) {
L.e(e);
}
return message;
}
// ===========================================
// UnackedMessagesProcessor
//
// [unack-msg-1] --500ms--> [unack-msg-2] --500ms--> [unack-msg-3] --500ms--> ...
//
// ===========================================
private static class UnackedMessagesProcessor {
interface OnCompletedCallback {
void onCompleted(int messageProcessedCount, int messageTotalCount);
}
private static final String LOG_START = "[UnackedMessagesProcessor] start process unacked messages, count: %d";
private static final String LOG_NEXT = "[UnackedMessagesProcessor] next unacked message, index:%d, message:%s";
private static final String LOG_COMPLETED = "[UnackedMessagesProcessor] index == size, finished, total unacked messages: %d";
private static final int WHAT = 1;
private static final long DELAY_MILLIS = 500; // 500ms
private Handler handler;
private PPMessageSDK messageSDK;
private List<String> unackedMessages;
private int index;
private boolean completed;
private OnCompletedCallback completedCallback;
public UnackedMessagesProcessor(PPMessageSDK messageSDK, final List<String> unackedMessages) {
this.handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == WHAT) {
int index = msg.arg1;
notifyMessageArrived(unackedMessages.get(index));
}
next();
}
};
this.messageSDK = messageSDK;
this.unackedMessages = unackedMessages;
this.index = -1;
setCompleted(false);
}
public void setCompletedCallback(OnCompletedCallback completedCallback) {
this.completedCallback = completedCallback;
}
public void start() {
if (unackedMessages == null ||
unackedMessages.isEmpty()) {
setCompleted(true);
return;
}
L.d(LOG_START, unackedMessages.size());
next();
}
public void stop() {
handler.removeMessages(WHAT);
setCompleted(true);
}
private void next() {
index++;
if (index < unackedMessages.size()) {
L.d(LOG_NEXT, index, unackedMessages.get(index));
Message message = handler.obtainMessage(WHAT);
message.arg1 = index;
handler.sendMessageDelayed(message, DELAY_MILLIS);
} else {
L.d(LOG_COMPLETED, unackedMessages.size());
stop();
}
}
private void notifyMessageArrived(String message) {
messageSDK.getNotification().notify(message);
}
public boolean isCompleted() {
return completed;
}
private void setCompleted(boolean completed) {
this.completed = completed;
if (completed) {
if (completedCallback != null) {
completedCallback.onCompleted(index, unackedMessages != null ? unackedMessages.size() : 0);
}
}
}
}
}
| mit |
alexjab/share-expenses | src/UserList.React.js | 1039 | 'use strict';
var UserList = React.createClass ({
handleDeleteUser: function (key) {
return this.props.handleDeleteUser (key);
},
render: function () {
var userContent;
var that = this;
if (this.props.users.length) {
var userList = this.props.users.map (function (user) {
return (
<li className="list-group-item" key={user.key}>
{user.name}
<span className="delete-button">
<i className="glyphicon glyphicon-remove action-icon" onClick={that.handleDeleteUser.bind (that, user.key)}></i>
</span>
</li>
);
});
userContent = (
<ul className="list-group">
{userList}
</ul>
);
} else {
userContent = (
<div className="panel-body">
No user yet.
</div>
);
}
return (
<div className="panel panel-info">
<div className="panel-heading">Users</div>
{userContent}
</div>
);
}
});
module.exports = UserList;
| mit |
danielrohers/bory | test/support/env.js | 37 | process.env.NO_DEPRECATION = 'bory';
| mit |
NikolaiMishev/Telerik-Academy | Module-1/03.CSharp OOP/OOP Principles - Part 1/03. Animal hierarchy/ProgramMain.cs | 323 |
namespace _03.Animal_hierarchy
{
using System;
using System.Collections.Generic;
public class ProgramMain
{
public static void Main()
{
Frog some = new Frog("froggy", Sex.Male, 2, "Forest Green");
Console.WriteLine(some.Jump());
}
}
}
| mit |
jarkko/raskaasti | spec/models_spec.rb | 11934 | require File.expand_path("model_factory", File.dirname(__FILE__))
require File.expand_path("spec_helper", File.dirname(__FILE__))
module ModelMatchers
class HavePage
def initialize(path)
@category = path
end
def matches?(article)
@article = article
article.categories.map { |c| c.path }.include?(@category)
end
def failure_message
"expected '#{@article.path}' to be assigned to #{@category}"
end
def negative_failure_message
"'#{@article.path}' should not be assigned to #{@category}"
end
end
def be_in_category(path)
HavePage.new(path)
end
end
describe "Page", :shared => true do
include ModelFactory
include ModelMatchers
def create_page(options)
super(options.merge(:ext => @extension))
end
before(:each) do
stub_configuration
end
after(:each) do
remove_fixtures
Nesta::FileModel.purge_cache
end
it "should be findable" do
create_page(:heading => "Apple", :path => "the-apple")
Nesta::Page.find_all.should have(1).item
end
it "should find by path" do
create_page(:heading => "Banana", :path => "banana")
Nesta::Page.find_by_path("banana").heading.should == "Banana"
end
it "should not find nonexistent page" do
Nesta::Page.find_by_path("no-such-page").should be_nil
end
it "should ensure file exists on instantiation" do
lambda {
Nesta::Page.new("no-such-file")
}.should raise_error(Sinatra::NotFound)
end
it "should reload cached files when modified" do
create_page(:path => "a-page", :heading => "Version 1")
File.stub!(:mtime).and_return(Time.new - 1)
Nesta::Page.find_by_path("a-page")
create_page(:path => "a-page", :heading => "Version 2")
File.stub!(:mtime).and_return(Time.new)
Nesta::Page.find_by_path("a-page").heading.should == "Version 2"
end
describe "with assigned pages" do
before(:each) do
@category = create_category
create_article(:heading => "Article 1", :path => "article-1")
create_article(
:heading => "Article 2",
:path => "article-2",
:metadata => {
"date" => "30 December 2008",
"categories" => @category.path
}
)
@article = create_article(
:heading => "Article 3",
:path => "article-3",
:metadata => {
"date" => "31 December 2008",
"categories" => @category.path
}
)
create_category(:path => "category-2",
:metadata => { "categories" => @category.path })
end
it "should find articles" do
@category.articles.should have(2).items
end
it "should list most recent articles first" do
@category.articles.first.path.should == @article.path
end
it "should find pages" do
@category.pages.should have(1).item
end
it "should not find pages scheduled in the future" do
future_date = (Time.now + 86400).strftime("%d %B %Y")
article = create_article(:heading => "Article 4",
:path => "foo/article-4",
:metadata => { "date" => future_date })
Nesta::Page.find_articles.detect{|a| a == article}.should be_nil
end
end
describe "when finding articles" do
before(:each) do
create_article(:heading => "Article 1", :path => "article-1")
create_article(:heading => "Article 2",
:path => "article-2",
:metadata => { "date" => "31 December 2008" })
create_article(:heading => "Article 3",
:path => "foo/article-3",
:metadata => { "date" => "30 December 2008" })
end
it "should only find pages with dates" do
articles = Nesta::Page.find_articles
articles.size.should > 0
Nesta::Page.find_articles.each { |page| page.date.should_not be_nil }
end
it "should return articles in reverse chronological order" do
article1, article2 = Nesta::Page.find_articles[0..1]
article1.date.should > article2.date
end
end
describe "when assigned to categories" do
before(:each) do
create_category(:heading => "Apple", :path => "the-apple")
create_category(:heading => "Banana", :path => "banana")
@article = create_article(
:metadata => { "categories" => "banana, the-apple" })
end
it "should be possible to list the categories" do
@article.categories.should have(2).items
@article.should be_in_category("the-apple")
@article.should be_in_category("banana")
end
it "should sort categories by heading" do
@article.categories.first.heading.should == "Apple"
end
it "should not be assigned to non-existant category" do
delete_page(:category, "banana", @extension)
@article.should_not be_in_category("banana")
end
end
it "should be able to find parent page" do
category = create_category(:path => "parent")
article = create_article(:path => "parent/child")
article.parent.should == category
end
it "should set parent to nil when at root" do
create_category(:path => "top-level").parent.should be_nil
end
describe "when not assigned to category" do
it "should have empty category list" do
article = create_article
Nesta::Page.find_by_path(article.path).categories.should be_empty
end
end
describe "without metadata" do
before(:each) do
create_article
@article = Nesta::Page.find_all.first
end
it "should use default layout" do
@article.layout.should == :layout
end
it "should use default template" do
@article.template.should == :page
end
it "should parse heading correctly" do
@article.to_html.should have_tag("h1", "My article")
end
it "should have default read more link text" do
@article.read_more.should == "Continue reading"
end
it "should not have description" do
@article.description.should be_nil
end
it "should not have keywords" do
@article.keywords.should be_nil
end
end
describe "with metadata" do
before(:each) do
@layout = "my_layout"
@template = "my_template"
@date = "07 September 2009"
@keywords = "things, stuff"
@description = "Page about stuff"
@summary = 'Multiline\n\nsummary'
@read_more = "Continue at your leisure"
@article = create_article(:metadata => {
"layout" => @layout,
"template" => @template,
"date" => @date.gsub("September", "Sep"),
"description" => @description,
"keywords" => @keywords,
"summary" => @summary,
"read more" => @read_more
})
end
it "should override default layout" do
@article.layout.should == @layout.to_sym
end
it "should override default template" do
@article.template.should == @template.to_sym
end
it "should set permalink from filename" do
@article.permalink.should == "my-article"
end
it "should set path from filename" do
@article.path.should == "article-prefix/my-article"
end
it "should retrieve heading" do
@article.heading.should == "My article"
end
it "should be possible to convert an article to HTML" do
@article.to_html.should have_tag("h1", "My article")
end
it "should not include metadata in the HTML" do
@article.to_html.should_not have_tag("p", /^Date/)
end
it "should not include heading in body" do
@article.body.should_not have_tag("h1", "My article")
end
it "should retrieve description from metadata" do
@article.description.should == @description
end
it "should retrieve keywords from metadata" do
@article.keywords.should == @keywords
end
it "should retrieve date published from metadata" do
@article.date.strftime("%d %B %Y").should == @date
end
it "should retrieve read more link from metadata" do
@article.read_more.should == @read_more
end
it "should retrieve summary text from metadata" do
@article.summary.should match(/#{@summary.split('\n\n').first}/)
end
it "should treat double newline chars as paragraph break in summary" do
@article.summary.should match(/#{@summary.split('\n\n').last}/)
end
end
describe "when checking last modification time" do
before(:each) do
create_article
@article = Nesta::Page.find_all.first
end
it "should check filesystem" do
mock_file_stat(:should_receive, @article.filename, "3 January 2009")
@article.last_modified.should == Time.parse("3 January 2009")
end
end
end
describe "All types of page" do
include ModelFactory
before(:each) do
stub_configuration
end
after(:each) do
remove_fixtures
Nesta::FileModel.purge_cache
end
it "should still return top level menu items" do
# Page.menu_items is deprecated; we're keeping it for the moment so
# that we don't break themes or code in local/app.rb (just yet).
page1 = create_category(:path => "page-1")
page2 = create_category(:path => "page-2")
create_menu([page1.path, page2.path].join("\n"))
Nesta::Page.menu_items.should == [page1, page2]
end
end
describe "Markdown page" do
before(:each) do
@extension = :mdown
end
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
create_page(
:path => "a-page",
:heading => "First heading",
:content => "# Second heading"
)
Nesta::Page.find_by_path("a-page").heading.should == "First heading"
end
end
describe "Haml page" do
before(:each) do
@extension = :haml
end
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
create_page(
:path => "a-page",
:heading => "First heading",
:content => "%h1 Second heading"
)
Nesta::Page.find_by_path("a-page").heading.should == "First heading"
end
end
describe "Textile page" do
before(:each) do
@extension = :textile
end
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
create_page(
:path => "a-page",
:heading => "First heading",
:content => "h1. Second heading"
)
Nesta::Page.find_by_path("a-page").heading.should == "First heading"
end
end
describe "Menu" do
include ModelFactory
before(:each) do
stub_configuration
@page = create_page(:path => "page-1")
end
after(:each) do
remove_fixtures
Nesta::FileModel.purge_cache
end
it "should find top level menu items" do
text = [@page.path, "no-such-page"].join("\n")
create_menu(text)
Nesta::Menu.top_level.should == [@page]
end
it "should find all items in the menu" do
create_menu(@page.path)
Nesta::Menu.full_menu.should == [@page]
Nesta::Menu.for_path('/').should == [@page]
end
describe "with nested sub menus" do
before(:each) do
(2..6).each do |i|
instance_variable_set("@page#{i}", create_page(:path => "page-#{i}"))
end
text = <<-EOF
#{@page.path}
#{@page2.path}
#{@page3.path}
#{@page4.path}
#{@page5.path}
#{@page6.path}
EOF
create_menu(text)
end
it "should return top level menu items" do
Nesta::Menu.top_level.should == [@page, @page5]
end
it "should return full tree of menu items" do
Nesta::Menu.full_menu.should ==
[@page, [@page2, [@page3, @page4]], @page5, [@page6]]
end
it "should return part of the tree of menu items" do
Nesta::Menu.for_path(@page2.path).should == [@page2, [@page3, @page4]]
end
it "should deem menu for path that isn't in menu to be nil" do
Nesta::Menu.for_path('wibble').should be_nil
end
end
end
| mit |
andreykata/SoftUni | Programming Basics/2016 June/CSharpProgrammingBasic02SimpleCalculation/Problem14/Properties/AssemblyInfo.cs | 1394 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem14")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem14")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c9ec6ca7-2ee3-4750-8a8c-f0a13d5af7f9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
peferron/algo | bloom_filter/javascript/hash.js | 507 | export default function hash(factor, modulo, str) {
const h = rawHash(factor, str) % modulo;
if (h < 0) {
return h + modulo;
}
return h;
}
function rawHash(factor, str) {
let h = 0;
for (let i = 0; i < str.length; i += 1) {
h = factor * h + str.charCodeAt(i);
// Bitwise arithmetic forces the result to be a 32-bit integer (see ECMAScript spec).
// Other than that, h |= 0 (shorthand for h = h | 0) is a no-op.
h |= 0;
}
return h;
}
| mit |
jehovahsays/hiddenwiki | examples/chat/node_modules/php-embed/src/node_php_phpobject_class.cc | 40439 | // A PHP object, wrapped for access by JavaScript (node/v8).
// Inspired by v8js_object_export in the v8js PHP extension.
// Copyright (c) 2015 C. Scott Ananian <cscott@cscott.net>
#include "src/node_php_phpobject_class.h"
#include <cassert>
#define __STDC_FORMAT_MACROS // Sometimes necessary to get PRIu32
#include <cinttypes> // For PRIu32
#include <cstdio> // For snprintf
#include <vector>
#include "nan.h"
extern "C" {
#include "main/php.h"
#include "Zend/zend.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h" // for zend_call_method_with_*
#include "Zend/zend_types.h"
#include "ext/standard/php_string.h" // for php_strtolower
}
#include "src/macros.h"
#include "src/messages.h"
// For some reason, travis still doesn't like PRIu32.:
#ifndef PRIu32
# warning "Your compiler seems to be broken."
# define PRIu32 "u"
#endif
#define THROW_IF_EXCEPTION(fallback_msg, defaultValue) \
do { \
if (msg.HasException()) { \
v8::Local<v8::Value> e = msg.exception().ToJs(channel_); \
Nan::MaybeLocal<v8::String> msg_str = Nan::To<v8::String>(e); \
if (msg_str.IsEmpty()) { \
Nan::ThrowError(fallback_msg); \
} else { \
Nan::ThrowError(msg_str.ToLocalChecked()); \
} \
return defaultValue; \
} \
} while (0)
namespace node_php_embed {
v8::Local<v8::Object> PhpObject::Create(MapperChannel *channel,
objid_t id) {
Nan::EscapableHandleScope scope;
PhpObject *obj = new PhpObject(channel, id);
v8::Local<v8::Value> argv[] = { Nan::New<v8::External>(obj) };
return scope.Escape(constructor()->NewInstance(1, argv));
}
void PhpObject::MaybeNeuter(MapperChannel *channel, v8::Local<v8::Object> obj) {
v8::Local<v8::FunctionTemplate> t = Nan::New(cons_template());
if (!t->HasInstance(obj)) {
// Nope, not a PhpObject.
return;
}
PhpObject *p = Unwrap<PhpObject>(obj);
if (p->channel_ != channel) {
// Already neutered, or else not from this request.
return;
}
p->channel_ = nullptr;
p->id_ = 0;
}
NAN_MODULE_INIT(PhpObject::Init) {
v8::Local<v8::String> class_name = NEW_STR("PhpObject");
v8::Local<v8::FunctionTemplate> tpl =
Nan::New<v8::FunctionTemplate>(PhpObject::New);
tpl->SetClassName(class_name);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
cons_template().Reset(tpl);
Nan::SetNamedPropertyHandler(tpl->InstanceTemplate(),
PhpObject::PropertyGet,
PhpObject::PropertySet,
PhpObject::PropertyQuery,
PhpObject::PropertyDelete,
PhpObject::PropertyEnumerate);
Nan::SetIndexedPropertyHandler(tpl->InstanceTemplate(),
PhpObject::IndexGet,
PhpObject::IndexSet,
PhpObject::IndexQuery,
PhpObject::IndexDelete,
PhpObject::IndexEnumerate);
Nan::Set(target, class_name, constructor());
}
PhpObject::~PhpObject() {
// XXX remove from mapping table, notify PHP.
TRACE("JS deallocate");
}
NAN_METHOD(PhpObject::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("You must use `new` with this constructor.");
}
if (!info[0]->IsExternal()) {
return Nan::ThrowTypeError("This constructor is for internal use only.");
}
TRACE(">");
// This object was made by PhpObject::Create()
PhpObject *obj = reinterpret_cast<PhpObject*>
(v8::Local<v8::External>::Cast(info[0])->Value());
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
TRACE("<");
}
NAN_PROPERTY_GETTER(PhpObject::PropertyGet) {
TRACEX("> %s", *Nan::Utf8String(property));
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Property(PropertyOp::GETTER, property));
TRACEX("< %s", *Nan::Utf8String(property));
}
NAN_INDEX_GETTER(PhpObject::IndexGet) {
TRACEX("> [%" PRIu32 "]", index);
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Property(PropertyOp::GETTER, index));
TRACEX("< [%" PRIu32 "]", index);
}
NAN_PROPERTY_SETTER(PhpObject::PropertySet) {
TRACEX("> %s", *Nan::Utf8String(property));
// XXX for async access, it seems like we might be able to lie about
// what the result of the Set operation is -- that is,
// `(x = y) !== y`. Perhaps `x = y` could resolve to a `Promise`?
// (or else v8 will just ignore our return value.)
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Property(PropertyOp::SETTER, property, value));
TRACEX("< %s", *Nan::Utf8String(property));
}
NAN_INDEX_SETTER(PhpObject::IndexSet) {
TRACEX("> [%" PRIu32 "]", index);
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Property(PropertyOp::SETTER, index, value));
TRACEX("< [%" PRIu32 "]", index);
}
NAN_PROPERTY_DELETER(PhpObject::PropertyDelete) {
TRACEX("> %s", *Nan::Utf8String(property));
PhpObject *p = Unwrap<PhpObject>(info.Holder());
v8::Local<v8::Value> r = p->Property(PropertyOp::DELETER, property);
if (!r.IsEmpty()) {
info.GetReturnValue().Set(Nan::To<v8::Boolean>(r).ToLocalChecked());
}
TRACEX("< %s", *Nan::Utf8String(property));
}
NAN_INDEX_DELETER(PhpObject::IndexDelete) {
TRACEX("> [%" PRIu32 "]", index);
PhpObject *p = Unwrap<PhpObject>(info.Holder());
v8::Local<v8::Value> r = p->Property(PropertyOp::DELETER, index);
if (!r.IsEmpty()) {
info.GetReturnValue().Set(Nan::To<v8::Boolean>(r).ToLocalChecked());
}
TRACEX("< [%" PRIu32 "]", index);
}
NAN_PROPERTY_QUERY(PhpObject::PropertyQuery) {
TRACEX("> %s", *Nan::Utf8String(property));
PhpObject *p = Unwrap<PhpObject>(info.Holder());
v8::Local<v8::Value> r = p->Property(PropertyOp::QUERY, property);
if (!r.IsEmpty()) {
info.GetReturnValue().Set(Nan::To<v8::Integer>(r).ToLocalChecked());
}
TRACEX("< %s", *Nan::Utf8String(property));
}
NAN_INDEX_QUERY(PhpObject::IndexQuery) {
TRACEX("> [%" PRIu32 "]", index);
PhpObject *p = Unwrap<PhpObject>(info.Holder());
v8::Local<v8::Value> r = p->Property(PropertyOp::QUERY, index);
if (!r.IsEmpty()) {
info.GetReturnValue().Set(Nan::To<v8::Integer>(r).ToLocalChecked());
}
TRACEX("< [%" PRIu32 "]", index);
}
NAN_PROPERTY_ENUMERATOR(PhpObject::PropertyEnumerate) {
TRACE(">");
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Enumerate(EnumOp::ONLY_PROPERTY));
TRACE("<");
}
NAN_INDEX_ENUMERATOR(PhpObject::IndexEnumerate) {
TRACE(">");
PhpObject *p = Unwrap<PhpObject>(info.Holder());
info.GetReturnValue().Set(p->Enumerate(EnumOp::ONLY_INDEX));
TRACE("<");
}
// Helper function, called from PHP only
static bool IsArrayAccess(zval *z TSRMLS_DC) {
if (Z_TYPE_P(z) != IS_OBJECT) {
TRACE("false (not object)");
return false;
}
zend_class_entry *ce = Z_OBJCE_P(z);
bool has_array_access = false;
bool has_countable = false;
for (zend_uint i = 0; i < ce->num_interfaces; i++) {
if (strcmp(ce->interfaces[i]->name, "ArrayAccess") == 0) {
has_array_access = true;
}
if (strcmp(ce->interfaces[i]->name, "Countable") == 0) {
has_countable = true;
}
if (has_array_access && has_countable) {
// Bail early from loop, don't need to look further.
TRACE("true");
return true;
}
}
TRACE("false");
return false;
}
class PhpObject::PhpEnumerateMsg : public MessageToPhp {
public:
PhpEnumerateMsg(ObjectMapper *m, Nan::Callback *callback, bool is_sync,
EnumOp op, objid_t obj)
: MessageToPhp(m, callback, is_sync), op_(op) {
obj_.SetJsObject(obj);
}
protected:
void InPhp(PhpObjectMapper *m TSRMLS_DC) override {
ZVal obj{ZEND_FILE_LINE_C};
obj_.ToPhp(m, obj TSRMLS_CC);
assert(obj.IsObject() || obj.IsArray());
bool is_array_access = IsArrayAccess(obj.Ptr() TSRMLS_CC);
if (obj.IsArray() || is_array_access) {
return ArrayEnum(m, op_, obj, is_array_access, &retval_, &exception_
TSRMLS_CC);
}
// XXX unimplemented
retval_.SetArrayByValue(0, [](uint32_t idx, Value& v) { });
}
private:
Value obj_;
EnumOp op_;
};
v8::Local<v8::Array> PhpObject::Enumerate(EnumOp which) {
Nan::EscapableHandleScope scope;
if (id_ == 0) {
Nan::ThrowError("Access to PHP request after it has completed.");
return scope.Escape(v8::Local<v8::Array>());
}
PhpEnumerateMsg msg(channel_, nullptr, true, // Sync call.
which, id_);
channel_->SendToPhp(&msg, MessageFlags::SYNC);
THROW_IF_EXCEPTION("PHP exception thrown during property enumeration",
v8::Local<v8::Array>());
if (!msg.retval().IsEmpty()) {
assert(msg.retval().IsArrayByValue());
return scope.Escape(msg.retval().ToJs(channel_).As<v8::Array>());
}
return scope.Escape(v8::Local<v8::Array>());
}
class PhpObject::PhpPropertyMsg : public MessageToPhp {
public:
PhpPropertyMsg(ObjectMapper *m, Nan::Callback *callback, bool is_sync,
PropertyOp op, objid_t obj, v8::Local<v8::String> name,
v8::Local<v8::Value> value, bool is_index)
: MessageToPhp(m, callback, is_sync), op_(op), name_(m, name),
is_index_(is_index) {
obj_.SetJsObject(obj);
if (!value.IsEmpty()) {
value_.Set(m, value);
}
}
protected:
// JS uses an empty return value to indicate lookup should continue
// up the prototype chain.
bool IsEmptyRetvalOk() override {
return (op_ != PropertyOp::SETTER);
}
void InPhp(PhpObjectMapper *m TSRMLS_DC) override {
ZVal obj{ZEND_FILE_LINE_C}, zname{ZEND_FILE_LINE_C};
ZVal value{ZEND_FILE_LINE_C};
obj_.ToPhp(m, obj TSRMLS_CC); name_.ToPhp(m, zname TSRMLS_CC);
assert(obj.IsObject() || obj.IsArray());
assert(zname.IsString());
if (!value_.IsEmpty()) {
value_.ToPhp(m, value TSRMLS_CC);
}
// Arrays are handled in a separate method (but the ZVals here will
// handle the memory management for us).
bool is_array_access = IsArrayAccess(obj.Ptr() TSRMLS_CC);
if (obj.IsArray() || is_array_access) {
return ArrayInPhp(m, obj, is_array_access, zname, value TSRMLS_CC);
}
const char *cname = Z_STRVAL_P(*zname);
uint cname_len = Z_STRLEN_P(*zname);
const char *method_name;
uint method_name_len;
zend_class_entry *scope, *ce;
zend_function *method_ptr = nullptr;
zval *php_value;
ce = scope = Z_OBJCE_P(*obj);
// Property names with embedded nulls are special to PHP.
if (cname_len == 0 ||
cname[0] == '\0' ||
(cname_len > 1 && cname[0] == '$' && cname[1] == '\0')) {
exception_.SetConstantString("Attempt to access private property");
return;
}
/* First, check the (case-insensitive) method table */
char *lower = static_cast<char*>(alloca(cname_len + 1));
memcpy(lower, cname, cname_len + 1);
php_strtolower(lower, cname_len);
method_name = lower;
method_name_len = cname_len;
// toString() -> __tostring()
if (cname_len == 8 && strcmp(cname, "toString") == 0) {
method_name = ZEND_TOSTRING_FUNC_NAME;
method_name_len = sizeof(ZEND_TOSTRING_FUNC_NAME) - 1;
}
bool is_constructor =
(cname_len == 11 && strcmp(cname, "constructor") == 0);
// Fake __call implementation. If you wanted the PHP method named __call,
// either use `_Call` (since PHP is case-insensitive), or else use
// `obj.__call('__call', ...)`.
bool is_magic_call = (cname_len == 6 && strcmp(cname, "__call") == 0);
// Leading '$' means property, not method.
bool is_forced_property = (cname_len > 0 && cname[0] == '$');
if (is_constructor || is_magic_call ||
((!is_forced_property) &&
zend_hash_find(&ce->function_table, method_name, method_name_len + 1,
reinterpret_cast<void**>(&method_ptr)) == SUCCESS &&
// Allow only public methods:
((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) &&
// No __construct, __destruct(), or __clone() functions
((method_ptr->common.fn_flags &
(ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) == 0))) {
if (op_ == PropertyOp::GETTER) {
if (is_constructor) {
// Don't set a return value here, i.e. indicate that we don't
// have a special value. V8 "knows" the constructor anyways
// (from the template) and will use that.
retval_.SetEmpty();
} else {
if (is_magic_call) {
// Fake __call implementation
// If there's an actual PHP __call, then you'd have to invoke
// it as "__Call" or else use `obj.__call("__call", ...)`
retval_.SetMethodThunk();
} else {
retval_.SetMethodThunk();
}
}
} else if (op_ == PropertyOp::QUERY) {
// Methods are not enumerable.
retval_.SetInt(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
} else if (op_ == PropertyOp::SETTER) {
// Lie: methods are read-only, don't allow setting this property.
retval_.Set(m, *value TSRMLS_CC);
retval_.TakeOwnership();
} else if (op_ == PropertyOp::DELETER) {
// Can't delete methods.
retval_.SetBool(false); // "property found here, but not deletable"
} else {
assert(false); // Shouldn't reach here!
}
} else {
if (is_forced_property) {
// This is a property (not a method).
cname = estrndup(cname + 1, --cname_len);
zname.SetString(cname, cname_len, 0);
}
if (op_ == PropertyOp::GETTER) {
/* Nope, not a method -- must be a (case-sensitive) property */
zend_property_info *property_info =
zend_get_property_info(ce, *zname, 1 TSRMLS_CC);
if (property_info && property_info->flags & ZEND_ACC_PUBLIC) {
php_value = zend_read_property(nullptr, obj.Ptr(), cname, cname_len,
true TSRMLS_CC);
// Special case uninitialized_zval_ptr and return an empty value
// (indicating that we don't intercept this property) if the
// property doesn't exist.
if (php_value == EG(uninitialized_zval_ptr)) {
retval_.SetEmpty();
} else {
retval_.Set(m, php_value TSRMLS_CC);
retval_.TakeOwnership();
/* We don't own the reference to php_value... unless the
* returned refcount was 0, in which case the below code
* will free it. */
zval_add_ref(&php_value);
zval_ptr_dtor(&php_value);
}
} else if ((SUCCESS ==
zend_hash_find(&ce->function_table, "__get", 6,
reinterpret_cast<void**>(&method_ptr)))
/* Allow only public methods */
&& ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
/* Okay, let's call __get. */
zend_call_method_with_1_params(obj.PtrPtr(), ce, nullptr, "__get",
&php_value, zname.Ptr());
retval_.Set(m, php_value TSRMLS_CC);
retval_.TakeOwnership();
zval_ptr_dtor(&php_value);
} else {
retval_.SetEmpty();
}
} else if (op_ == PropertyOp::SETTER) {
assert(!value_.IsEmpty());
zend_property_info *property_info =
zend_get_property_info(ce, zname.Ptr(), 1 TSRMLS_CC);
if (property_info && (property_info->flags & ZEND_ACC_PUBLIC) != 0) {
zend_update_property(scope, obj.Ptr(), cname, cname_len,
value.Ptr() TSRMLS_CC);
retval_.Set(m, value.Ptr() TSRMLS_CC);
retval_.TakeOwnership();
} else if (
zend_hash_find(&ce->function_table, "__set", 6,
reinterpret_cast<void**>(&method_ptr)) == SUCCESS
/* Allow only public methods */
&& ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
/* Okay, let's call __set. */
zend_call_method_with_2_params
(obj.PtrPtr(), ce, nullptr, "__set",
&php_value, zname.Ptr(), value.Ptr());
retval_.Set(m, value.Ptr() TSRMLS_CC);
retval_.TakeOwnership();
zval_ptr_dtor(&php_value);
} else if (property_info) {
// It's a property, but not a public one.
// Shouldn't ever get here, since zend_get_property_info() will
// return NULL if we don't have permission to access the property.
exception_.SetConstantString("Attempt to set private property");
} else {
// Okay, we need to be a little careful here:
// zend_get_property_info() returned NULL, but that may have
// been because there was a private property of this name.
// We don't want to create a new property shadowing it, that
// would effectively defeat the access modifier. So we need
// to redo a bit of the acces control checks from
// zend_get_property_info to ensure it's safe to create a
// new property.
if (zend_hash_find(&ce->properties_info, cname, cname_len + 1,
reinterpret_cast<void**>(&property_info)) ==
SUCCESS) {
// Hm, we found the property but zend_get_property_info
// told us it wasn't here. Must be an access issue.
// Silently refuse to set the value.
} else {
// Doesn't exist yet, create it!
zend_update_property(scope, obj.Ptr(), cname, cname_len,
value.Ptr() TSRMLS_CC);
}
retval_.Set(m, value.Ptr() TSRMLS_CC);
retval_.TakeOwnership();
}
} else if (op_ == PropertyOp::QUERY) {
const zend_object_handlers *h = Z_OBJ_HT_P(obj.Ptr());
if (h->has_property(obj.Ptr(), zname.Ptr(), 0
ZEND_HASH_KEY_NULL TSRMLS_CC)) {
retval_.SetInt(v8::None);
} else {
retval_.SetEmpty(); // "property not found here; keep looking"
}
} else if (op_ == PropertyOp::DELETER) {
const zend_object_handlers *h = Z_OBJ_HT_P(obj.Ptr());
zend_property_info *property_info =
zend_get_property_info(ce, zname.Ptr(), 1 TSRMLS_CC);
if (property_info && (property_info->flags & ZEND_ACC_PUBLIC) != 0) {
h->unset_property(obj.Ptr(), zname.Ptr()
ZEND_HASH_KEY_NULL TSRMLS_CC);
retval_.SetBool(true);
} else if (
zend_hash_find(&ce->function_table, "__unset", 8,
reinterpret_cast<void**>(&method_ptr)) == SUCCESS
/* Allow only public methods */
&& ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
/* Okay, let's call __unset. */
zend_call_method_with_1_params(obj.PtrPtr(), ce, nullptr, "__unset",
&php_value, zname.Ptr());
retval_.SetBool(true);
zval_ptr_dtor(&php_value);
} else if (property_info) {
// It's a property, but not a public one.
// Shouldn't ever get here, since zend_get_property_info() will
// return NULL if we don't have permission to access the property.
exception_.SetConstantString("Attempt to unset private property");
} else {
retval_.SetEmpty(); // "property not found here; keep looking"
}
} else {
/* shouldn't reach here! */
assert(false);
retval_.SetEmpty();
}
}
}
void ArrayInPhp(PhpObjectMapper *m, const ZVal &arr, bool is_array_access,
const ZVal &name, const ZVal &value TSRMLS_DC) {
assert(is_array_access ? arr.IsObject() : arr.IsArray());
const char *cname = Z_STRVAL_P(name.Ptr());
uint cname_len = Z_STRLEN_P(name.Ptr());
// Length is special
if (cname_len == 6 && 0 == strcmp(cname, "length")) {
if (op_ == PropertyOp::QUERY) {
// Length is not enumerable and not configurable, but *is* writable.
retval_.SetInt(v8::DontEnum|v8::DontDelete);
} else if (op_ == PropertyOp::GETTER || op_ == PropertyOp::SETTER) {
// Length property is "maximum index in hash", not "number of items"
return PhpObject::ArraySize(m, op_, EnumOp::ONLY_INDEX,
arr, is_array_access, value,
&retval_, &exception_ TSRMLS_CC);
} else if (op_ == PropertyOp::DELETER) {
// Can't delete the length property.
retval_.SetBool(false); // "property found here, but not deletable"
} else {
assert(false);
}
return;
}
// All-numeric keys are special
if (is_index_) {
return PhpObject::ArrayOp(m, op_, arr, is_array_access, name, value,
&retval_, &exception_ TSRMLS_CC);
}
// Special Map-like methods
bool map_method = false;
switch (cname_len) {
case 3:
map_method =
(0 == strcmp(cname, "get") ||
0 == strcmp(cname, "has") ||
0 == strcmp(cname, "set"));
break;
case 4:
map_method =
(0 == strcmp(cname, "size") ||
0 == strcmp(cname, "keys"));
break;
case 6:
map_method = (0 == strcmp(cname, "delete"));
break;
default:
break;
}
if (map_method) {
if (op_ == PropertyOp::QUERY) {
// Methods are not enumerable
retval_.SetInt(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
} else if (op_ == PropertyOp::GETTER) {
retval_.SetMethodThunk();
} else if (op_ == PropertyOp::SETTER) {
// Lie: methods are read-only, don't allow setting this property.
retval_.Set(m, value TSRMLS_CC);
retval_.TakeOwnership();
} else if (op_ == PropertyOp::DELETER) {
// Can't delete methods.
retval_.SetBool(false); // "property found here, but not deletable"
} else {
assert(false);
}
return;
}
// None of the above.
if (op_ == PropertyOp::SETTER) {
retval_.Set(m, value TSRMLS_CC); // Lie
retval_.TakeOwnership();
} else {
retval_.SetEmpty(); // "Not here, keep looking."
}
}
private:
PropertyOp op_;
Value obj_;
Value name_;
Value value_;
bool is_index_;
};
v8::Local<v8::Value> PhpObject::Property(PropertyOp op,
uint32_t index,
v8::Local<v8::Value> new_value) {
// Convert index to string
char buf[11]; // strlen("4294967295") == 10, plus null byte
snprintf(buf, sizeof(buf), "%" PRIu32, index);
return Property(op, NEW_STR(buf), new_value, true);
}
v8::Local<v8::Value> PhpObject::Property(PropertyOp op,
v8::Local<v8::String> property,
v8::Local<v8::Value> new_value,
bool is_index) {
Nan::EscapableHandleScope scope;
// First, check to see if this is a closed object.
if (id_ == 0) {
bool silent = (op == PropertyOp::QUERY);
// Special case requests to get `then`, since that's used when the
// main request code returns a value via a Promise, and we don't want
// that to fail until the user actually tries to do something with the
// returned value.
if (op == PropertyOp::GETTER && property->Length() == 4 &&
strcmp("then", *Nan::Utf8String(property)) == 0) {
silent = true;
}
if (!silent) {
Nan::ThrowError("Access to PHP request after it has completed.");
}
return scope.Escape(v8::Local<v8::Value>());
}
// XXX For async property access, might make a PromiseResolver
// and use that to create a callback.
PhpPropertyMsg msg(channel_, nullptr, true, // Sync call.
op, id_, property, new_value, is_index);
channel_->SendToPhp(&msg, MessageFlags::SYNC);
THROW_IF_EXCEPTION("PHP exception thrown during property access",
v8::Local<v8::Value>());
if (msg.retval().IsMethodThunk()) {
// Create a method thunk
v8::Local<v8::Array> data = Nan::New<v8::Array>(2);
Nan::Set(data, 0, handle()).FromJust();
Nan::Set(data, 1, property).FromJust();
return scope.Escape(Nan::New<v8::Function>(MethodThunk, data));
} else if (!msg.retval().IsEmpty()) {
return scope.Escape(msg.retval().ToJs(channel_));
}
return scope.Escape(v8::Local<v8::Value>());
}
class PhpObject::PhpInvokeMsg : public MessageToPhp {
public:
PhpInvokeMsg(ObjectMapper *m, Nan::Callback *callback, bool is_sync,
objid_t obj, v8::Local<v8::String> method,
const Nan::FunctionCallbackInfo<v8::Value> *info)
: MessageToPhp(m, callback, is_sync), method_(m, method),
argc_(info->Length()), argv_(),
should_convert_array_to_iterator_(false) {
obj_.SetJsObject(obj);
argv_.SetArrayByValue(argc_, [m, info](uint32_t idx, Value& v) {
v.Set(m, (*info)[idx]);
});
}
inline bool should_convert_array_to_iterator() {
return should_convert_array_to_iterator_;
}
protected:
bool IsEmptyRetvalOk() override {
// We use the empty value to indicate "undefined", which can't
// otherwise be represented in PHP.
return true;
}
void InPhp(PhpObjectMapper *m TSRMLS_DC) override {
ZVal obj{ZEND_FILE_LINE_C}, method{ZEND_FILE_LINE_C};
obj_.ToPhp(m, obj TSRMLS_CC);
method_.ToPhp(m, method TSRMLS_CC);
std::vector<ZVal> args;
args.reserve(argc_);
for (int i = 0; i < argc_; i++) {
args.emplace_back(ZEND_FILE_LINE_C);
argv_[i].ToPhp(m, args[i] TSRMLS_CC);
}
assert(obj.IsObject() || obj.IsArray());
assert(method.IsString());
// Arrays are handled in a separate method (but the ZVals here will
// handle the memory management for us).
bool is_array_access = IsArrayAccess(obj.Ptr() TSRMLS_CC);
if (obj.IsArray() || is_array_access) {
return ArrayInPhp(m, obj, is_array_access,
method, args.size(), args.data() TSRMLS_CC);
}
ZVal retval{ZEND_FILE_LINE_C};
// If the method name is __call, then shift the new method name off
// the front of the argument array.
zval *name = method.Ptr();
int first = 0;
if (Z_STRLEN_P(name) == 6 && 0 == strcmp(Z_STRVAL_P(name), "__call")) {
if (argc_ == 0 || !args[0].IsString()) {
zend_throw_exception_ex(
zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC,
"__call needs at least one argument, a string");
return;
}
name = args[0].Ptr(); first = 1;
}
std::vector<zval*> nargs(argc_ - first);
for (int i = first; i < argc_; i++) {
nargs[i - first] = args[i].Ptr();
}
// Ok, now actually invoke that PHP method!
call_user_function(EG(function_table), obj.PtrPtr(), name,
retval.Ptr(), nargs.size(), nargs.data() TSRMLS_CC);
if (EG(exception)) {
exception_.Set(m, EG(exception) TSRMLS_CC);
zend_clear_exception(TSRMLS_C);
} else {
retval_.Set(m, retval.Ptr() TSRMLS_CC);
retval_.TakeOwnership(); // This will outlive scope of `retval`
}
}
void ArrayInPhp(PhpObjectMapper *m, const ZVal &arr, bool is_array_access,
const ZVal &name, int argc, ZVal* argv TSRMLS_DC) {
assert(is_array_access ? arr.IsObject() : arr.IsArray());
assert(name.IsString());
#define THROW_IF_BAD_ARGS(meth, n) \
if (argc < n) { \
zend_throw_exception_ex( \
zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, \
"%s needs at least %d argument%s", meth, n, (n > 1) ? "s" : ""); \
return; \
} \
if (!argv[0].IsString()) { \
argv[0].Separate(); \
convert_to_string(argv[0].Ptr()); \
} \
assert(argv[0].IsString())
const char *cname = Z_STRVAL_P(name.Ptr());
uint cname_len = Z_STRLEN_P(name.Ptr());
// Special Map-like methods
switch (cname_len) {
case 3:
if (0 == strcmp(cname, "get")) {
THROW_IF_BAD_ARGS("get", 1);
ZVal ignore{ZEND_FILE_LINE_C};
return PhpObject::ArrayOp(m, PropertyOp::GETTER, arr, is_array_access,
argv[0], ignore, &retval_, &exception_
TSRMLS_CC);
}
if (0 == strcmp(cname, "has")) {
THROW_IF_BAD_ARGS("has", 1);
ZVal ignore{ZEND_FILE_LINE_C};
PhpObject::ArrayOp(m, PropertyOp::QUERY, arr, is_array_access,
argv[0], ignore, &retval_, &exception_ TSRMLS_CC);
// return true only if the property exists & is enumerable
if (retval_.IsEmpty()) {
retval_.SetBool(false);
} else {
retval_.ToPhp(m, ignore TSRMLS_CC);
assert(ignore.IsLong());
if ((Z_LVAL_P(ignore.Ptr()) & v8::DontEnum) != 0) {
retval_.SetBool(false);
} else {
retval_.SetBool(true);
}
}
return;
}
if (0 == strcmp(cname, "set")) {
THROW_IF_BAD_ARGS("set", 2);
return PhpObject::ArrayOp(m, PropertyOp::SETTER, arr, is_array_access,
argv[0], argv[1], &retval_, &exception_
TSRMLS_CC);
}
break;
case 4:
if (0 == strcmp(cname, "size")) {
// Size of all items, not just maximum index in hash.
ZVal ignore{ZEND_FILE_LINE_C};
return PhpObject::ArraySize(m, PropertyOp::GETTER, EnumOp::ALL,
arr, is_array_access, ignore,
&retval_, &exception_ TSRMLS_CC);
}
if (0 == strcmp(cname, "keys")) {
// Map#keys() should actually return an Iterator, not an array.
should_convert_array_to_iterator_ = true;
return PhpObject::ArrayEnum(m, EnumOp::ALL, arr, is_array_access,
&retval_, &exception_ TSRMLS_CC);
}
break;
case 6:
if (0 == strcmp(cname, "delete")) {
THROW_IF_BAD_ARGS("delete", 1);
ZVal ignore{ZEND_FILE_LINE_C};
PhpObject::ArrayOp(m, PropertyOp::DELETER, arr, is_array_access,
argv[0], ignore,
&retval_, &exception_ TSRMLS_CC);
retval_.SetBool(!retval_.IsEmpty());
return;
}
break;
default:
break;
}
// Shouldn't get here.
zend_throw_exception_ex(
zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC,
"bad method name");
}
private:
Value obj_;
Value method_;
int argc_;
Value argv_;
bool should_convert_array_to_iterator_;
};
void PhpObject::MethodThunk(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Array> data = info.Data().As<v8::Array>();
v8::Local<v8::Object> obj =
Nan::Get(data, 0).ToLocalChecked().As<v8::Object>();
v8::Local<v8::String> method =
Nan::Get(data, 1).ToLocalChecked().As<v8::String>();
PhpObject *p = Unwrap<PhpObject>(obj);
// Do the rest in a non-static method.
return p->MethodThunk_(method, info);
}
void PhpObject::MethodThunk_(v8::Local<v8::String> method,
const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (id_ == 0) {
return Nan::ThrowError("Invocation after PHP request has completed.");
}
PhpInvokeMsg msg(channel_, nullptr, true, // Sync call.
id_, method, &info);
channel_->SendToPhp(&msg, MessageFlags::SYNC);
THROW_IF_EXCEPTION("PHP exception thrown during method invocation", /* */);
if (msg.retval().IsEmpty()) {
info.GetReturnValue().Set(Nan::Undefined());
} else if (msg.should_convert_array_to_iterator()) {
// Map#keys() method should actually return an iterator, not an
// array, so call Array#values() on the result.
v8::Local<v8::Array> r = msg.retval().ToJs(channel_).As<v8::Array>();
v8::Local<v8::Object> values = Nan::Get(r, NEW_STR("values"))
.ToLocalChecked().As<v8::Object>();
Nan::MaybeLocal<v8::Value> newr =
Nan::CallAsFunction(values, r, 0, nullptr);
if (!newr.IsEmpty()) { info.GetReturnValue().Set(newr.ToLocalChecked()); }
} else {
info.GetReturnValue().Set(msg.retval().ToJs(channel_));
}
}
void PhpObject::ArrayAccessOp(PhpObjectMapper *m, PropertyOp op,
const ZVal &arr, const ZVal &name, const ZVal &value,
Value *retval, Value *exception TSRMLS_DC) {
assert(arr.IsObject() && name.IsString());
zval *rv = nullptr;
zval **objpp = const_cast<ZVal&>(arr).PtrPtr();
// Make sure calling the interface method doesn't screw with `name`;
// this is done in spl_array.c, presumably for good reason.
ZVal offset(name.Ptr() ZEND_FILE_LINE_CC);
offset.Separate();
if (op == PropertyOp::QUERY) {
zend_call_method_with_1_params(objpp, nullptr, nullptr, "offsetExists",
&rv, offset.Ptr());
if (rv && zend_is_true(rv)) {
retval->SetInt(v8::None);
} else {
retval->SetEmpty();
}
if (rv) { zval_ptr_dtor(&rv); }
} else if (op == PropertyOp::GETTER) {
zval *rv2;
// We need to call offsetExists to distinguish between "missing offset"
// and "offset present, but with value NULL."
zend_call_method_with_1_params(objpp, nullptr, nullptr, "offsetExists",
&rv2, offset.Ptr());
if (rv2 && zend_is_true(rv2)) {
zend_call_method_with_1_params(objpp, nullptr, nullptr, "offsetGet",
&rv, offset.Ptr());
}
if (rv) {
retval->Set(m, rv TSRMLS_CC);
retval->TakeOwnership();
zval_ptr_dtor(&rv);
} else {
retval->SetEmpty();
}
if (rv2) { zval_ptr_dtor(&rv2); }
} else if (op == PropertyOp::SETTER) {
zend_call_method_with_2_params(objpp, nullptr, nullptr, "offsetSet",
NULL, offset.Ptr(), value.Ptr());
retval->Set(m, value TSRMLS_CC);
retval->TakeOwnership();
} else if (op == PropertyOp::DELETER) {
zend_call_method_with_1_params(objpp, nullptr, nullptr, "offsetUnset",
NULL, offset.Ptr());
retval->SetBool(true);
} else {
assert(false);
}
}
void PhpObject::ArrayOp(PhpObjectMapper *m, PropertyOp op,
const ZVal &arr, bool is_array_access,
const ZVal &name, const ZVal &value,
Value *retval, Value *exception TSRMLS_DC) {
if (is_array_access) {
// Split this case into its own function to avoid cluttering this one
// with two dissimilar cases.
return ArrayAccessOp(m, op, arr, name, value, retval, exception TSRMLS_CC);
}
assert(arr.IsArray() && name.IsString());
HashTable *arrht = Z_ARRVAL_P(arr.Ptr());
const char *cname = Z_STRVAL_P(name.Ptr());
uint cname_len = Z_STRLEN_P(name.Ptr());
zval **r;
if (op == PropertyOp::QUERY) {
if (zend_symtable_find(arrht, cname, cname_len + 1,
reinterpret_cast<void**>(&r)) == SUCCESS) {
if (Z_TYPE_PP(r) == IS_NULL) {
// "isset" semantics, say it's not enumerable if null
retval->SetInt(v8::DontEnum);
} else {
retval->SetInt(v8::None);
}
} else {
retval->SetEmpty();
}
} else if (op == PropertyOp::GETTER) {
if (zend_symtable_find(arrht, cname, cname_len + 1,
reinterpret_cast<void**>(&r)) == SUCCESS) {
retval->Set(m, *r TSRMLS_CC);
retval->TakeOwnership();
} else {
retval->SetEmpty();
}
} else if (op == PropertyOp::SETTER) {
zval *z = const_cast<ZVal &>(value).Escape();
zend_symtable_update(arrht, cname, cname_len + 1, &z, sizeof(z), NULL);
retval->Set(m, z TSRMLS_CC);
retval->TakeOwnership();
} else if (op == PropertyOp::DELETER) {
if (SUCCESS == zend_symtable_del(arrht, cname, cname_len + 1)) {
retval->SetBool(true);
} else {
retval->SetEmpty();
}
} else {
assert(false);
}
}
void PhpObject::ArrayEnum(PhpObjectMapper *m, EnumOp op,
const ZVal &arr, bool is_array_access,
Value *retval, Value *exception TSRMLS_DC) {
// XXX unimplemented
retval->SetArrayByValue(0, [](uint32_t idx, Value& v) { });
}
void PhpObject::ArraySize(PhpObjectMapper *m, PropertyOp op, EnumOp which,
const ZVal &arr, bool is_array_access,
const ZVal &value,
Value *retval, Value *exception TSRMLS_DC) {
if (is_array_access) {
assert(arr.IsObject());
zval **objpp = const_cast<ZVal&>(arr).PtrPtr();
zval *rv;
if (op == PropertyOp::GETTER) {
if (which == EnumOp::ALL) {
zend_call_method_with_0_params(objpp, nullptr, nullptr, "count", &rv);
ZVal r(rv ZEND_FILE_LINE_CC);
if (rv) { zval_ptr_dtor(&rv); }
r.Separate();
convert_to_long(r.Ptr());
retval->Set(m, r TSRMLS_CC);
retval->TakeOwnership();
} else if (which == EnumOp::ONLY_INDEX) {
// XXX Not supported by standard ArrayAccess API.
// XXX Define our own Js\Array interface, and try to call
// a `getLength` method in it, iff the object implements
// Js\Array?
retval->SetInt(0);
}
} else if (op == PropertyOp::SETTER && which == EnumOp::ONLY_INDEX) {
// XXX Not supported by standard ArrayAccess API.
// XXX Define our own Js\Array interface, and try to call
// a `setLength` method in it, iff the object implements
// Js\Array?
retval->Set(m, value TSRMLS_CC);
retval->TakeOwnership();
}
} else {
assert(arr.IsArray());
HashTable *arrht = Z_ARRVAL_P(arr.Ptr());
if (op == PropertyOp::GETTER) {
if (which == EnumOp::ALL) {
// This is "number of items" (including string keys), not "max index"
retval->SetInt(zend_hash_num_elements(arrht));
return;
} else if (which == EnumOp::ONLY_INDEX) {
retval->SetInt(zend_hash_next_free_element(arrht));
}
} else if (op == PropertyOp::SETTER && which == EnumOp::ONLY_INDEX) {
if (!value.IsLong()) {
// convert to int
const_cast<ZVal&>(value).Separate();
convert_to_long(value.Ptr());
}
if (value.IsLong() && Z_LVAL_P(value.Ptr()) >= 0) {
ulong nlen = Z_LVAL_P(value.Ptr());
ulong olen = zend_hash_next_free_element(arrht);
if (nlen < olen) {
// We have to iterate here, rather unfortunate.
// XXX We could look at zend_hash_num_elements() and
// iterate over the elements if num_elements < (olen - nlen)
for (ulong i = nlen; i < olen; i++) {
zend_hash_index_del(arrht, i);
}
}
// This is quite dodgy, since we're going to write the
// nNextFreeElement field directly. Perhaps not portable!
arrht->nNextFreeElement = nlen;
}
retval->Set(m, value TSRMLS_CC);
retval->TakeOwnership();
}
}
}
} // namespace node_php_embed
| mit |
sporchia/alttp_vt_randomizer | resources/lang/en/watch.php | 1937 | <?php
return [
'header' => 'Join the Adventure!',
'cards' => [
'twitch' => [
'header' => 'Twitch',
'content' => [
'With so much going on, there’s always a race to watch! Follow these networks and never miss a match!',
],
'button' => 'ALttP:R Twitch Community',
],
'tournament' => [
'header' => 'Tournaments',
'sections' => [
[
'header' => 'Upcoming Tournaments',
'content' => [
'Join us for the 2019 Main Tournament starting this October! Join our <a href="https://discord.gg/alttprandomizer" target="_blank" rel="noopener noreferrer">Discord</a> community to stay up to date!',
],
],
[
'header' => '2018 Spring Invitational',
'content' => [
'The 2018 Spring Invitational has wrapped up!',
'<a href="https://www.youtube.com/playlist?list=PLdoWICJMgPKWZKYiZD1uLn529-fdHHqUK" target="_blank" rel="noopener noreferrer">Watch all the matches here!</a>',
'<div class="center"><iframe allow="encrypted-media" allowfullscreen frameborder="0" gesture="media" height="315" src="https://www.youtube.com/embed/iAmfUsMJONw?rel=0" width="560"></iframe></div>',
],
],
],
],
'youtube' => [
'header' => 'Youtube',
'content' => [
'<div class="center"><a class="btn btn-secondary btn-lg btn-xl "href="https://www.youtube.com/channel/UCBMMk0WJAeldNv4fI9juovA" rel="noopener noreferrer" role="button" target="_blank">ALttP:R Youtube Channel</a></div>',
'Subscribe to our Youtube channel for updates, tournament highlights, and more!',
]
],
],
];
| mit |
sitespeedio/sitespeed.io | lib/plugins/gcs/index.js | 3962 | 'use strict';
const fs = require('fs-extra');
const path = require('path');
const readdir = require('recursive-readdir');
// Documentation of @google-cloud/storage: https://cloud.google.com/nodejs/docs/reference/storage/2.3.x/Bucket#upload
const { Storage } = require('@google-cloud/storage');
const log = require('intel').getLogger('sitespeedio.plugin.gcs');
const throwIfMissing = require('../../support/util').throwIfMissing;
async function uploadLatestFiles(dir, gcsOptions, prefix) {
function ignoreDirs(file, stats) {
return stats.isDirectory();
}
const storage = new Storage({
projectId: gcsOptions.projectId,
keyFilename: gcsOptions.key
});
const bucket = storage.bucket(gcsOptions.bucketname);
const files = await readdir(dir, [ignoreDirs]);
const promises = [];
for (let file of files) {
promises.push(uploadFile(file, bucket, gcsOptions, prefix, dir, true));
}
return Promise.all(promises);
}
async function upload(dir, gcsOptions, prefix) {
const files = await readdir(dir);
const promises = [];
const storage = new Storage({
projectId: gcsOptions.projectId,
keyFilename: gcsOptions.key
});
const bucket = storage.bucket(gcsOptions.bucketname);
for (let file of files) {
const stats = fs.statSync(file);
if (stats.isFile()) {
promises.push(uploadFile(file, bucket, gcsOptions, prefix, dir));
} else {
log.debug(`Will not upload ${file} since it is not a file`);
}
}
return Promise.all(promises);
}
async function uploadFile(
file,
bucket,
gcsOptions,
prefix,
baseDir,
noCacheTime
) {
const subPath = path.relative(baseDir, file);
const fileName = path.join(gcsOptions.path || prefix, subPath);
const params = {
public: !!gcsOptions.public,
destination: fileName,
resumable: false,
validation: 'crc32c',
gzip: !!gcsOptions.gzip,
metadata: {
metadata: {
cacheControl: 'public, max-age=' + noCacheTime ? 0 : 31536000
}
}
};
return bucket.upload(file, params);
}
module.exports = {
open(context, options) {
this.gcsOptions = options.gcs;
this.options = options;
this.make = context.messageMaker('gcs').make;
throwIfMissing(this.gcsOptions, ['bucketname'], 'gcs');
this.storageManager = context.storageManager;
},
async processMessage(message, queue) {
if (message.type === 'sitespeedio.setup') {
// Let other plugins know that the GCS plugin is alive
queue.postMessage(this.make('gcs.setup'));
} else if (message.type === 'html.finished') {
const make = this.make;
const gcsOptions = this.gcsOptions;
const baseDir = this.storageManager.getBaseDir();
log.info(
`Uploading ${baseDir} to Google Cloud Storage bucket ${gcsOptions.bucketname}, this can take a while ...`
);
try {
await upload(
baseDir,
gcsOptions,
this.storageManager.getStoragePrefix()
);
if (this.options.copyLatestFilesToBase) {
const rootPath = path.resolve(baseDir, '..');
const dirsAsArray = rootPath.split(path.sep);
const rootName = dirsAsArray.slice(-1)[0];
await uploadLatestFiles(rootPath, gcsOptions, rootName);
}
log.info('Finished upload to Google Cloud Storage');
if (gcsOptions.public) {
log.info(
'Uploaded results on Google Cloud storage are publicly readable'
);
}
if (gcsOptions.removeLocalResult) {
await fs.remove(baseDir);
log.debug(`Removed local files and directory ${baseDir}`);
} else {
log.debug(
`Local result files and directories are stored in ${baseDir}`
);
}
} catch (e) {
queue.postMessage(make('error', e));
log.error('Could not upload to Google Cloud Storage', e);
}
queue.postMessage(make('gcs.finished'));
}
}
};
| mit |
XDrake99/PICalculator | core/src/main/java/it/cavallium/warppi/gui/expression/blocks/Block.java | 2733 | package it.cavallium.warppi.gui.expression.blocks;
import it.cavallium.warppi.device.display.DisplayOutputDevice;
import it.cavallium.warppi.gui.GraphicalElement;
import it.cavallium.warppi.gui.expression.Caret;
import it.cavallium.warppi.gui.expression.ExtraMenu;
import it.cavallium.warppi.gui.expression.InputContext;
import it.cavallium.warppi.gui.graphicengine.Renderer;
import it.cavallium.warppi.math.MathContext;
import it.cavallium.warppi.math.parser.features.interfaces.Feature;
import it.cavallium.warppi.util.Error;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public abstract class Block implements TreeBlock, GraphicalElement {
protected boolean small;
protected int width;
protected int height;
protected int line;
protected TreeContainer parent;
public Block() {
}
/**
* Copy
* @param b
*/
public Block(TreeContainer parent, Block b) {
this.small = b.small;
this.width = b.width;
this.height = b.height;
this.line = b.line;
this.parent = parent;
}
/**
*
* @param r
* Graphic Renderer class.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
* @param small
*/
public abstract void draw(DisplayOutputDevice ge, Renderer r, int x, int y, Caret caret);
public abstract boolean putBlock(Caret caret, Block newBlock);
public abstract boolean delBlock(Caret caret);
public abstract BlockReference<?> getBlock(Caret caret);
/**
* Used only to get inner blocks when deleting the parent block.
* @return every block of every inner container, or null if empty
*/
public abstract ObjectArrayList<Block> getInnerBlocks();
public abstract ObjectArrayList<BlockContainer> getInnerContainers();
@Override
public abstract void recomputeDimensions();
public abstract int computeCaretMaxBound();
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getLine() {
return line;
}
public int getCaretDeltaPositionAfterCreation() {
return 1;
}
public boolean isSmall() {
return small;
}
public abstract void setSmall(boolean small);
public ExtraMenu<?> getExtraMenu() {
return null;
}
public abstract Feature toFeature(MathContext context) throws Error;
@Override
public TreeContainer getParentContainer() {
return parent;
}
@Override
public boolean hasParent() {
return parent != null;
}
public void setParent(final TreeContainer parent) {
this.parent = parent;
}
public abstract Block clone(TreeContainer parent, InputContext ic);
}
| mit |
Croissong/nussnougat | web/react/src/routes/index.js | 970 | import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
// NOTE: here we're making use of the `resolve.root` configuration
// option in webpack, which allows us to specify import paths as if
// they were from the root of the ~/src directory. This makes it
// very easy to navigate to files regardless of how deeply nested
// your current file is.
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
import HomeView from 'views/HomeView/HomeView'
import DonkebapView from 'views/DonkebapView/DonkebapView'
import CroissongView from 'views/CroissongView/CroissongView'
import CounterView from 'views/CounterView/CounterView'
export default (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomeView} />
<Route path='donkebap' component={DonkebapView} />
<Route path='croissong' component={CroissongView} />
<Route path='counter' component={CounterView} />
<Redirect from='*' to='/404' />
</Route>
)
| mit |
davellx/PrintJob | dependencies/android/src/org/haxe/extension/PrintJob.java | 3565 | package org.haxe.extension;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.support.v4.print.PrintHelper;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.net.Uri;
import java.io.File;
/*
You can use the Android Extension class in order to hook
into the Android activity lifecycle. This is not required
for standard Java code, this is designed for when you need
deeper integration.
You can access additional references from the Extension class,
depending on your needs:
- Extension.assetManager (android.content.res.AssetManager)
- Extension.callbackHandler (android.os.Handler)
- Extension.mainActivity (android.app.Activity)
- Extension.mainContext (android.content.Context)
- Extension.mainView (android.view.View)
You can also make references to static or instance methods
and properties on Java classes. These classes can be included
as single files using <java path="to/File.java" /> within your
project, or use the full Android Library Project format (such
as this example) in order to include your own AndroidManifest
data, additional dependencies, etc.
These are also optional, though this example shows a static
function for performing a single task, like returning a value
back to Haxe from Java.
*/
public class PrintJob extends Extension {
public static void printBitmapFile(String path, String id){
PrintHelper photoPrinter = new PrintHelper(mainActivity);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
Bitmap bitmap = BitmapFactory.decodeFile(path);
photoPrinter.printBitmap("Volvic - " + id, bitmap);
}
public static void printBitmapFileBluetooth(String path, String type){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType(type);
File file = new File(path);
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
mainActivity.startActivity(Intent.createChooser(i, "Send Image"));
}
/**
* Called when an activity you launched exits, giving you the requestCode
* you started it with, the resultCode it returned, and any additional data
* from it.
*/
public boolean onActivityResult (int requestCode, int resultCode, Intent data) {
return true;
}
/**
* Called when the activity is starting.
*/
public void onCreate (Bundle savedInstanceState) {
}
/**
* Perform any final cleanup before an activity is destroyed.
*/
public void onDestroy () {
}
/**
* Called as part of the activity lifecycle when an activity is going into
* the background, but has not (yet) been killed.
*/
public void onPause () {
}
/**
* Called after {@link #onStop} when the current activity is being
* re-displayed to the user (the user has navigated back to it).
*/
public void onRestart () {
}
/**
* Called after {@link #onRestart}, or {@link #onPause}, for your activity
* to start interacting with the user.
*/
public void onResume () {
}
/**
* Called after {@link #onCreate} — or after {@link #onRestart} when
* the activity had been stopped, but is now again being displayed to the
* user.
*/
public void onStart () {
}
/**
* Called when the activity is no longer visible to the user, because
* another activity has been resumed and is covering this one.
*/
public void onStop () {
}
} | mit |
deanshackley/CondenserDotNet | src/CondenserDotNet.Configuration/Consul/IConfigSource.cs | 519 | using System.Collections.Generic;
using System.Threading.Tasks;
namespace CondenserDotNet.Configuration.Consul
{
public interface IConfigSource
{
object CreateWatchState();
string FormValidKey(string keyPath);
Task<(bool success, Dictionary<string, string> dictionary)> GetKeysAsync(string keyPath);
Task<(bool success, Dictionary<string, string> update)> TryWatchKeysAsync(string keyPath, object state);
Task<bool> TrySetKeyAsync(string keyPath, string value);
}
} | mit |
nabab/bbn | src/bbn/User/Manager.php | 30464 | <?php
/**
* @package user
*/
namespace bbn\User;
use bbn;
use bbn\X;
use stdClass;
/**
* A class for managing users
*
*
* @author Thomas Nabet <thomas.nabet@gmail.com>
* @copyright BBN Solutions
* @since Apr 4, 2011, 23:23:55 +0000
* @category Authentication
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @version 0.2r89
*/
class Manager
{
protected static $admin_group;
protected static $dev_group;
protected $messages = [
'creation' => [
'subject' => "Account created",
'link' => "",
'text' => "
A new user has been created for you.<br>
Please click the link below in order to activate your account:<br>
%1\$s"
],
'password' => [
'subject' => "Password change",
'link' => "",
'text' => "
You can click the following link to change your password:<br>
%1\$s"
],
'hotlink' => [
'subject' => "Hotlink",
'link' => "",
'text' => "
You can click the following link to access directly your account:<br>
%1\$s"
]
];
// 1 day
protected $hotlink_length = 86400;
protected $list_fields;
protected $usrcls;
protected $mailer = false;
protected $db;
protected $class_cfg = false;
public function getListFields()
{
return $this->list_fields;
}
public function getMailer()
{
if (!$this->mailer) {
$this->mailer = $this->usrcls->getMailer();
}
return $this->mailer;
}
public function findSessions(string $id_user=null, int $minutes = 5): array
{
$cfg = [
'table' => $this->class_cfg['tables']['sessions'],
'fields' => [],
'where' => [
[
'field' => $this->class_cfg['arch']['sessions']['last_activity'],
'operator' => '<',
'value' => 'DATE_SUB(NOW(), INTERVAL '.$this->db->csn($this->class_cfg['sess_length'], true).' MINUTE)'
]
]
];
if (!\is_null($id_user)) {
$cfg['where'][] = [
'field' => $this->class_cfg['arch']['sessions']['id_user'],
'value' => $id_user
];
}
return $this->db->rselectAll($cfg);
}
public function destroySessions(string $id_user, int $minutes = 5): bool
{
$sessions = $this->findSessions($id_user, $minutes);
//$num = count($sessions);
foreach ($sessions as $s){
$this->db->delete($this->class_cfg['tables']['sessions'], [$this->class_cfg['arch']['sessions']['id'] => $s['id']]);
}
return true;
}
/**
* @param bbn\User $obj A user's connection object (\connection or subclass)
*
*/
public function __construct(bbn\User $obj)
{
if (\is_object($obj) && method_exists($obj, 'getClassCfg')) {
$this->usrcls = $obj;
$this->class_cfg = $this->usrcls->getClassCfg();
if (!$this->list_fields) {
$this->setDefaultListFields();
}
$this->db = $this->usrcls->getDbInstance();
}
}
public function isOnline(string $id_user, int $delay = 180): bool
{
$a =& $this->class_cfg['arch'];
$t =& $this->class_cfg['tables'];
if (($max = $this->db->selectOne($t['sessions'], 'MAX('.$a['sessions']['last_activity'].')', ['id_user' => $id_user]))
&& (strtotime($max) > (time() - $delay))
) {
return true;
}
return false;
}
/**
* Returns all the users' groups - with or without admin
* @param bool $adm
* @return array|false
*/
public function groups(): array
{
$a =& $this->class_cfg['arch'];
$t =& $this->class_cfg['tables'];
$id = $this->db->cfn($a['groups']['id'], $t['groups']);
$users_id = $this->db->cfn($a['users']['id'], $t['users'], 1);
$db =& $this->db;
$fields = \array_map(
function ($g) use ($db, $t) {
return $db->cfn($g, $t['groups']);
}, \array_values($a['groups'])
);
$fields['num'] = "COUNT($users_id)";
return $this->db->rselectAll(
[
'table' => $t['groups'],
'fields' => $fields,
'join' => [[
'table' => $t['users'],
'type' => 'left',
'on' => [
'conditions' => [[
'field' => $this->db->cfn($a['users']['id_group'], $t['users']),
'exp' => $id
]]
]
]],
'group_by' => [$id]
]
);
}
public function textValueGroups()
{
return $this->db->rselectAll(
$this->class_cfg['tables']['groups'], [
'value' => $this->class_cfg['arch']['groups']['id'],
'text' => $this->class_cfg['arch']['groups']['group'],
]
);
}
public function getEmail(string $id): ?string
{
if (bbn\Str::isUid($id)) {
$email = $this->db->selectOne($this->class_cfg['tables']['users'], $this->class_cfg['arch']['users']['email'], [$this->class_cfg['arch']['users']['id'] => $id]);
if ($email && bbn\Str::isEmail($email)) {
return $email;
}
}
return null;
}
public function getList(string $group_id = null): array
{
$db =& $this->db;
$arch =& $this->class_cfg['arch'];
$s =& $arch['sessions'];
$tables =& $this->class_cfg['tables'];
if (!empty($arch['users']['username'])) {
$sort = $arch['users']['username'];
}
elseif (!empty($arch['users']['login'])) {
$sort = $arch['users']['login'];
}
else{
$sort = $arch['users']['email'];
}
$sql = "SELECT ";
$done = [];
foreach ($arch['users'] as $n => $f){
if (!\in_array($f, $done)) {
$sql .= $db->cfn($f, $tables['users'], 1).', ';
array_push($done, $f);
}
}
$gr = !empty($group_id) && \bbn\Str::isUid($group_id) ? "AND " . $db->cfn($arch['groups']['id'], $tables['groups'], 1) . " = UNHEX('$group_id')" : '';
$sql .= "
MAX({$db->cfn($s['last_activity'], $tables['sessions'], 1)}) AS {$db->csn($s['last_activity'], 1)},
COUNT({$db->cfn($s['sess_id'], $tables['sessions'])}) AS {$db->csn($s['sess_id'], 1)}
FROM {$db->escape($tables['users'])}
JOIN {$db->tsn($tables['groups'], 1)}
ON {$db->cfn($arch['users']['id_group'], $tables['users'], 1)} = {$db->cfn($arch['groups']['id'], $tables['groups'], 1)}
$gr
LEFT JOIN {$db->tsn($tables['sessions'])}
ON {$db->cfn($s['id_user'], $tables['sessions'], 1)} = {$db->cfn($arch['users']['id'], $tables['users'], 1)}
WHERE {$db->cfn($arch['users']['active'], $tables['users'], 1)} = 1
GROUP BY {$db->cfn($arch['users']['id'], $tables['users'], 1)}
ORDER BY {$db->cfn($sort, $tables['users'], 1)}";
return $db->getRows($sql);
}
public function getUser(string $id): ?array
{
$u = $this->class_cfg['arch']['users'];
if (bbn\Str::isUid($id)) {
$where = [$u['id'] => $id];
}
else{
$where = [$u['login'] => $id];
}
if ($user = $this->db->rselect(
$this->class_cfg['tables']['users'],
array_values($u),
$where
)
) {
if ($session = $this->db->rselect(
$this->class_cfg['tables']['sessions'],
array_values($this->class_cfg['arch']['sessions']),
[$this->class_cfg['arch']['sessions']['id_user'] => $user[$u['id']]],
[$this->class_cfg['arch']['sessions']['last_activity'] => 'DESC']
)
) {
$session['id_session'] = $session['id'];
}
else{
$session = array_fill_keys(
array_values($this->class_cfg['arch']['sessions']),
''
);
$session['id_session'] = false;
}
return array_merge($session, $user);
}
return null;
}
public function getGroup(string $id): ?array
{
$g = $this->class_cfg['arch']['groups'];
if ($group = $this->db->rselect(
$this->class_cfg['tables']['groups'], [], [
$g['id'] => $id
]
)
) {
$group[$g['cfg']] = $group[$g['cfg']] ? json_decode($group[$g['cfg']], 1) : [];
return $group;
}
return null;
}
public function getGroupByCode(string $code): ?array
{
$g = $this->class_cfg['arch']['groups'];
if ($group = $this->db->rselect(
$this->class_cfg['tables']['groups'], [], [
$g['code'] => $code
]
)
) {
$group[$g['cfg']] = $group[$g['cfg']] ? json_decode($group[$g['cfg']], 1) : [];
return $group;
}
return null;
}
public function getUsers($group_id = null): array
{
return $this->db->getColArray(
"
SELECT ".$this->class_cfg['arch']['users']['id']."
FROM ".$this->class_cfg['tables']['users']."
WHERE {$this->db->escape($this->class_cfg['tables']['users'].'.'.$this->class_cfg['arch']['users']['active'])} = 1
AND ".$this->class_cfg['arch']['users']['id_group']." ".( $group_id ? "= ".(int)$group_id : "!= 1" )
);
}
public function fullList(): array
{
$r = [];
$u = $this->class_cfg['arch']['users'];
foreach ($this->db->rselectAll('bbn_users') as $a){
$r[] = [
'value' => $a[$u['id']],
'text' => $this->getName($a, false),
'id_group' => $a[$u['id_group']],
'active' => $a[$u['active']] ? true : false
];
}
return $r;
}
public function getUserId(string $login): ?string
{
return $this->db->selectOne(
$this->class_cfg['tables']['users'],
$this->class_cfg['arch']['users']['id'],
[
$this->class_cfg['arch']['users']['login'] => $login
]
);
}
public function getAdminGroup(): ?string
{
if (!self::$admin_group) {
if ($res = $this->db->selectOne(
$this->class_cfg['tables']['groups'],
$this->class_cfg['arch']['groups']['id'],
[
$this->class_cfg['arch']['groups']['code'] => 'admin'
]
)
) {
self::setAdminGroup($res);
}
}
return self::$admin_group;
}
public function getDevGroup(): ?string
{
if (!self::$dev_group) {
if ($res = $this->db->selectOne(
$this->class_cfg['tables']['groups'],
$this->class_cfg['arch']['groups']['id'],
[
$this->class_cfg['arch']['groups']['code'] => 'dev'
]
)
) {
self::setDevGroup($res);
}
}
return self::$dev_group;
}
public function getName($user, $full = true)
{
if (!\is_array($user)) {
$user = $this->getUser($user);
}
if (\is_array($user)) {
$idx = 'email';
if (!empty($this->class_cfg['arch']['users']['username'])) {
$idx = 'username';
}
elseif (!empty($this->class_cfg['arch']['users']['login'])) {
$idx = 'login';
}
return $user[$this->class_cfg['arch']['users'][$idx]];
}
return '';
}
public function getGroupType(string $id_group): ?string
{
$g =& $this->class_cfg['arch']['groups'];
return $this->db->selectOne($this->class_cfg['tables']['groups'], $g['type'], [$g['id'] => $id_group]);
}
/**
* Creates a new user and returns its configuration (with the new ID)
*
* @param array $cfg A configuration array
* @return array|false
*/
public function add(array $cfg): ?array
{
$u =& $this->class_cfg['arch']['users'];
$fields = array_unique(array_values($u));
$cfg[$u['active']] = 1;
$cfg[$u['cfg']] = new stdClass();
foreach ($cfg as $k => $v){
if (!\in_array($k, $fields)) {
$cfg[$u['cfg']]->$k = $v;
unset($cfg[$k]);
}
}
$cfg[$u['cfg']] = json_encode($cfg[$u['cfg']]);
if (isset($cfg['id'])) {
unset($cfg['id']);
}
if (!empty($cfg[$u['id_group']])) {
$group = $this->getGroupType($cfg[$u['id_group']]);
switch ($group) {
case 'real':
if (bbn\Str::isEmail($cfg[$u['email']])
&& $this->db->insert($this->class_cfg['tables']['users'], $cfg)
) {
$cfg[$u['id']] = $this->db->lastId();
// Envoi d'un lien
if (!empty($this->class_cfg['arch']['hotlinks'])) {
$this->makeHotlink($cfg[$this->class_cfg['arch']['users']['id']], 'creation');
}
return $cfg;
}
break;
case 'api':
$cfg[$u['email']] = null;
$cfg[$u['login']] = null;
if ($this->db->insert($this->class_cfg['tables']['users'], $cfg)) {
$cfg[$u['id']] = $this->db->lastId();
return $cfg;
}
break;
}
}
return null;
}
/**
* Creates a new user and returns its configuration (with the new ID)
*
* @param array $cfg A configuration array
* @return array|false
*/
public function edit(array $cfg, string $id_user = null): ?array
{
$u =& $this->class_cfg['arch']['users'];
$fields = array_unique(array_values($this->class_cfg['arch']['users']));
$cfg[$u['active']] = 1;
if (!empty($this->class_cfg['arch']['users']['cfg'])) {
if (empty($cfg[$this->class_cfg['arch']['users']['cfg']])) {
$cfg[$this->class_cfg['arch']['users']['cfg']] = [];
}
elseif (is_string($cfg[$this->class_cfg['arch']['users']['cfg']])) {
$cfg[$this->class_cfg['arch']['users']['cfg']] = json_decode($cfg[$this->class_cfg['arch']['users']['cfg']], true);
}
foreach ($cfg as $k => $v){
if (!\in_array($k, $fields)) {
$cfg[$this->class_cfg['arch']['users']['cfg']][$k] = $v;
unset($cfg[$k]);
}
}
$cfg[$this->class_cfg['arch']['users']['cfg']] = json_encode($cfg[$this->class_cfg['arch']['users']['cfg']]);
}
else {
foreach ($cfg as $k => $v){
if (!\in_array($k, $fields)) {
unset($cfg[$k]);
}
}
}
if (!$id_user && isset($cfg[$u['id']])) {
$id_user = $cfg[$u['id']];
}
if ($id_user && ( !isset($cfg[$this->class_cfg['arch']['users']['email']])
|| bbn\Str::isEmail($cfg[$this->class_cfg['arch']['users']['email']]) )
) {
if ($this->db->update(
$this->class_cfg['tables']['users'], $cfg, [
$u['id'] => $id_user
]
)
) {
$cfg['id'] = $id_user;
return $cfg;
}
}
return null;
}
public function copy(string $type, string $id, array $data): ?string
{
$pref = Preferences::getPreferences();
$cfg = $pref->getClassCfg();
switch ($type) {
case 'user':
if ($src = $this->getUser($id)) {
$data = X::mergeArrays($src, $data);
unset($data[$this->class_cfg['arch']['users']['id']]);
$col = $cfg['arch']['user_options']['id_user'];
$id_new = $this->add($data);
}
break;
case 'group':
if ($src = $this->getGroup($id)) {
$data = X::mergeArrays($src, $data);
unset($data[$this->class_cfg['arch']['groups']['id']]);
$col = $cfg['arch']['user_options']['id_group'];
$id_new = $this->groupInsert($data);
}
break;
}
if (!empty($id_new)) {
if ($options = $this->getOptions($type, $id)) {
$ids = [];
foreach ($options as $o) {
$old_id = $o['id'];
unset($o['id']);
$o[$col] = $id_new;
if ($this->db->insertIgnore($cfg['table'], $o)) {
$ids[$old_id] = $this->db->lastId();
}
}
$bids = [];
foreach ($ids as $oid => $nid) {
$bits = $this->db->rselectAll(
$cfg['tables']['user_options_bits'], [], [
$cfg['arch']['user_options_bits']['id_user_option'] => $oid,
$cfg['arch']['user_options_bits']['id_parent'] => null
]
);
foreach ($bits as $bit) {
$old_id = $bit[$cfg['arch']['user_options_bits']['id']];
unset($bit[$cfg['arch']['user_options_bits']['id']]);
$bit[$cfg['arch']['user_options_bits']['id_user_option']] = $nid;
$this->db->insert($cfg['tables']['user_options_bits'], $bit);
$bids[$old_id] = $this->db->lastId();
}
}
$remaining = -1;
$before = 0;
$done = [];
while ($remaining && ($before !== $remaining)) {
if ($remaining === -1) {
$before = 0;
}
else {
$before = $remaining;
}
$remaining = 0;
foreach ($ids as $oid => $nid) {
if (in_array($nid, $done)) {
continue;
}
$bits = $this->db->rselectAll(
$cfg['tables']['user_options_bits'], [], [
$cfg['arch']['user_options_bits']['id_user_option'] => $oid,
[$cfg['arch']['user_options_bits']['id_parent'], 'isnotnull']
]
);
if (!count($bits)) {
$done[] = $nid;
continue;
}
foreach ($bits as $bit) {
$old_id = $bit[$cfg['arch']['user_options_bits']['id']];
if (isset($bids[$old_id])) {
continue;
}
if (!isset($bids[$bit[$cfg['arch']['user_options_bits']['id_parent']]])) {
$remaining++;
}
else {
unset($bit[$cfg['arch']['user_options_bits']['id']]);
$bit[$cfg['arch']['user_options_bits']['id_user_option']] = $nid;
$bit[$cfg['arch']['user_options_bits']['id_parent']] = $bids[$bit[$cfg['arch']['user_options_bits']['id_parent']]];
$this->db->insert($cfg['tables']['user_options_bits'], $bit);
$bids[$old_id] = $this->db->lastId();
}
}
}
}
}
return $id_new;
}
return null;
}
public function sendMail(string $id_user, string $subject, string $text, array $attachments = []): ?int
{
if (($usr = $this->getUser($id_user)) && $usr['email']) {
if (!$this->getMailer()) {
//return mail($usr['email'], $subject, $text);
throw new \Exception(X::_("Impossible to make hotlinks without a proper mailer parameter"));
}
return $this->mailer->send(
[
'to' => $usr['email'],
'subject' => $subject,
'text' => $text,
'attachments' => $attachments
]
);
}
return null;
}
public function setPassword($id, $pass)
{
return (bool)$this->db->insert(
$this->class_cfg['tables']['passwords'], [
$this->class_cfg['arch']['passwords']['pass'] => $this->_hash($pass),
$this->class_cfg['arch']['passwords']['id_user'] => $id,
$this->class_cfg['arch']['passwords']['added'] => date('Y-m-d H:i:s')
]
);
}
/**
*
* @param string $id_user User ID
* @param string $message Type of the message
* @param int $exp Timestamp of the expiration date
* @return manager
*/
public function makeHotlink(string $id_user, string $message = 'hotlink', $exp = null): self
{
if (!isset($this->messages[$message]) || empty($this->messages[$message]['link'])) {
switch ($message)
{
case 'hotlink':
if ($path = bbn\Mvc::getPluginUrl('appui-usergroup')) {
$this->messages[$message]['link'] = BBN_URL.$path.'/main/profile';
}
break;
case 'creation':
if ($path = bbn\Mvc::getPluginUrl('appui-core')) {
$this->messages[$message]['link'] = BBN_URL.$path.'/login/%s';
}
break;
case 'password':
if ($path = bbn\Mvc::getPluginUrl('appui-core')) {
$this->messages[$message]['link'] = BBN_URL.$path.'/login/%s';
}
break;
}
if (empty($this->messages[$message]['link'])) {
throw new \Exception(X::_("Impossible to make hotlinks without a link configured"));
}
}
if ($usr = $this->getUser($id_user)) {
// Expiration date
if (!\is_int($exp) || ($exp < 1)) {
$exp = time() + $this->hotlink_length;
}
$hl =& $this->class_cfg['arch']['hotlinks'];
// Expire existing valid hotlinks
$this->db->update(
$this->class_cfg['tables']['hotlinks'], [
$hl['expire'] => date('Y-m-d H:i:s')
],[
[$hl['id_user'], '=', $id_user],
[$hl['expire'], '>', date('Y-m-d H:i:s')]
]
);
$magic = $this->usrcls->makeMagicString();
// Create hotlink
$this->db->insert(
$this->class_cfg['tables']['hotlinks'], [
$hl['magic'] => $magic['hash'],
$hl['id_user'] => $id_user,
$hl['expire'] => date('Y-m-d H:i:s', $exp)
]
);
$id_link = $this->db->lastId();
$link = "?id=$id_link&key=".$magic['key'];
$this->sendMail(
$id_user,
$this->messages[$message]['subject'],
sprintf($this->messages[$message]['text'], sprintf($this->messages[$message]['link'], $link))
);
}
else{
X::log("User $id_user not found");
throw new \Exception(X::_('User not found'));
}
return $this;
}
/**
*
* @param int $id_user User ID
* @param int $id_group Group ID
* @return manager
*/
public function setUniqueGroup(string $id_user, string $id_group): bool
{
return (bool)$this->db->update(
$this->class_cfg['tables']['users'], [
$this->class_cfg['arch']['users']['id_group'] => $id_group
], [
$this->class_cfg['arch']['users']['id'] => $id_user
]
);
}
public function userHasOption(string $id_user, string $id_option, bool $with_group = true): bool
{
if ($with_group && $user = $this->getUser($id_user)) {
$id_group = $user[$this->class_cfg['arch']['users']['id_group']];
if ($this->groupHasOption($id_group, $id_option)) {
return true;
}
}
if ($pref = Preferences::getPreferences()) {
if ($cfg = $pref->getClassCfg()) {
return $this->db->count(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_user'] => $id_user
]
) ? true : false;
}
}
return false;
}
public function groupHasOption(string $id_group, string $id_option): bool
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
return $this->db->count(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_group'] => $id_group
]
) ? true : false;
}
return false;
}
public function getOptions(string $type, string $id): ?array
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
if (stripos($type, 'group') === 0) {
return $this->db->rselectAll(
$cfg['table'], [], [
$cfg['arch']['user_options']['id_group'] => $id
]
);
}
elseif (stripos($type, 'user') === 0) {
return $this->db->rselectAll(
$cfg['table'], [], [
$cfg['arch']['user_options']['id_user'] => $id
]
);
}
}
return null;
}
public function userInsertOption(string $id_user, string $id_option): bool
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
return (bool)$this->db->insertIgnore(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_user'] => $id_user
]
);
}
return false;
}
public function groupInsertOption(string $id_group, string $id_option): bool
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
return (bool)$this->db->insertIgnore(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_group'] => $id_group
]
);
}
return false;
}
public function userDeleteOption(string $id_user, string $id_option): bool
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
return (bool)$this->db->deleteIgnore(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_user'] => $id_user
]
);
}
return false;
}
public function groupDeleteOption(string $id_group, string $id_option): bool
{
if (($pref = Preferences::getPreferences())
&& ($cfg = $pref->getClassCfg())
) {
return (bool)$this->db->deleteIgnore(
$cfg['table'], [
$cfg['arch']['user_options']['id_option'] => $id_option,
$cfg['arch']['user_options']['id_group'] => $id_group
]
);
}
return false;
}
public function groupNumUsers(string $id_group): int
{
$u =& $this->class_cfg['arch']['users'];
return $this->db->count(
$this->class_cfg['tables']['users'], [
$u['id_group'] => $id_group
]
);
}
public function groupInsert(array $data): ?string
{
$g = $this->class_cfg['arch']['groups'];
if (isset($data[$g['group']])) {
if (!empty($data[$g['cfg']]) && is_array($data[$g['cfg']])) {
$data[$g['cfg']] = json_encode($data[$g['cfg']]);
}
if ($this->db->insert(
$this->class_cfg['tables']['groups'],
[
$g['group'] => $data[$g['group']],
$g['code'] => $data[$g['code']] ?? null,
$g['cfg'] => !empty($g['cfg']) && !empty($data[$g['cfg']]) ? $data[$g['cfg']] : '{}'
]
)
) {
return $this->db->lastId();
}
}
return null;
}
public function groupEdit(string $id, array $data): bool
{
$g = $this->class_cfg['arch']['groups'];
if (!empty($data[$g['group']])) {
if (!empty($data[$g['cfg']]) && is_array($data[$g['cfg']])) {
$data[$g['cfg']] = json_encode($data[$g['cfg']]);
}
return (bool)$this->db->update(
$this->class_cfg['tables']['groups'],
[
$g['group'] => $data[$g['group']],
$g['code'] => $data[$g['code']] ?? null,
$g['cfg'] => !empty($g['cfg']) && !empty($data[$g['cfg']]) ? $data[$g['cfg']] : '{}'
],
[$g['id'] => $id]
);
}
return false;
}
public function groupRename(string $id, string $name): bool
{
$g = $this->class_cfg['arch']['groups'];
return (bool)$this->db->update(
$this->class_cfg['tables']['groups'], [
$g['group'] => $name
], [
$g['id'] => $id
]
);
}
public function groupSetCfg(string $id, array $cfg): bool
{
$g = $this->class_cfg['arch']['groups'];
return (bool)$this->db->update(
$this->class_cfg['tables']['groups'], [
$g['cfg'] => $cfg ?: '{}'
], [
$g['id'] => $id
]
);
}
public function groupDelete(string $id): bool
{
$g = $this->class_cfg['arch']['groups'];
if ($this->groupNumUsers($id)) {
/** @todo Error management */
throw new \Exception(X::_("Impossible to delete this group as it has users"));
}
return (bool)$this->db->delete(
$this->class_cfg['tables']['groups'], [
$g['id'] => $id
]
);
}
/**
* @param int $id_user User ID
*
* @return int|false Update result
*/
public function deactivate(string $id_user): bool
{
$update = [
$this->class_cfg['arch']['users']['active'] => 0,
$this->class_cfg['arch']['users']['email'] => null,
];
if (!empty($this->class_cfg['arch']['users']['login'])) {
$update[$this->class_cfg['arch']['users']['login']] = null;
}
if ($this->db->update(
$this->class_cfg['tables']['users'], $update, [
$this->class_cfg['arch']['users']['id'] => $id_user
]
)
) {
// Deleting existing sessions
$this->db->delete($this->class_cfg['tables']['sessions'], [$this->class_cfg['arch']['sessions']['id_user'] => $id_user]);
return true;
}
return false;
}
/**
* @param int $id_user User ID
*
* @return manager
*/
public function reactivate(string $id_user): bool
{
return (bool)$this->db->update(
$this->class_cfg['tables']['users'], [
$this->class_cfg['arch']['users']['active'] => 1
], [
$this->class_cfg['arch']['users']['id'] => $id_user
]
);
}
public function addPermission(string $id_perm, string $id_user = null, string $id_group = null, int $public = 0): bool
{
if (!$id_group && !$id_user && !$public) {
throw new \Exception("No paraneters!");
}
return (bool)$this->db->insertIgnore(
'bbn_users_options',
[
'id_option' => $id_perm,
'id_user' => $id_user,
'id_group' => $id_group,
'public' => $public
]
);
}
public function removePermission(string $id_perm, string $id_user = null, string $id_group = null, int $public = 0): bool
{
if (!$id_group && !$id_user && !$public) {
throw new \Exception("No paraneters!");
}
return (bool)$this->db->deleteIgnore(
'bbn_users_options',
[
'id_option' => $id_perm,
'id_user' => $id_user,
'id_group' => $id_group,
'public' => $public
]
);
}
public function createPermission(string $path)
{
return false;
}
public function deletePermission(string $id_perm): bool
{
return false;
}
protected function setDefaultListFields()
{
$fields = $this->class_cfg['arch']['users'];
unset($fields['id'], $fields['active'], $fields['cfg']);
$this->list_fields = [];
foreach ($fields as $n => $f){
if (!\in_array($f, $this->list_fields)) {
$this->list_fields[$n] = $f;
}
}
}
protected static function setAdminGroup($id)
{
self::$admin_group = $id;
}
protected static function setDevGroup($id)
{
self::$dev_group = $id;
}
/**
* Use the configured hash function to encrypt a password string.
*
* @param string $st The string to crypt
* @return string
*/
private function _hash(string $st): string
{
if (!function_exists($this->class_cfg['encryption'])) {
$this->class_cfg['encryption'] = 'sha256';
}
return $this->class_cfg['encryption']($st);
}
}
| mit |
alexbaroni/genem | spec/spec_helper.rb | 173 | $: << File.join(File.dirname(__FILE__), "/../lib" )
require 'rubygems'
require 'spec'
require 'fileutils'
require 'win32console' if RUBY_PLATFORM =~ /win32/
require 'genem'
| mit |
mitschabaude/nanopores | nanopores/scripts/test_survival.py | 3783 | from nanopores import *
from nanopores.physics.exittime import ExitTimeProblem
from dolfin import *
import math
# @Benjamin, Gregor TODO:
# -) check permittivity and surface charge of ahem
# -) what biased voltage to use?
geo_params = dict(
l3 = 30.,
l4 = 30.,
R = 40.,
x0 = [5., 0., 10.], # |x0| > 2.2
exit_i = None,
)
phys_params = dict(
bV = .1,
ahemqs = 0.01,
rTarget = 0.5*nm,
)
print
print "--- MESHING"
print
t = Timer("meshing")
meshdict = generate_mesh(7., "aHem", **geo_params)
print "Mesh generation time:",t.stop()
#print "Mesh file:",meshdict["fid_xml"]
#print "Mesh metadata:"
#for item in meshdict["meta"].items():
# print "%s = %s" %item
#print
t = Timer("reading geometry")
geo = geo_from_xml("aHem")
print "Geo generation time:",t.stop()
#print "Geo params:", geo.params
#print "Geo physical domains:", geo._physical_domain
#print "Geo physical boundaries:", geo._physical_boundary
#plot(geo.boundaries)
#plot(geo.submesh("solid"))
#plot(geo.submesh("exittime"))
phys = Physics("pore_molecule", geo, **phys_params)
x0 = geo.params["x0"]
r0 = math.sqrt(sum(x**2 for x in x0))
rnear = r0 - geo.params["rMolecule"]
rfar = r0 + geo.params["rMolecule"]
xnear = map(lambda x: rnear/r0*x, x0)
xfar = map(lambda x: rfar/r0*x, x0)
def avg(u, meas):
return assemble(u*meas)/assemble(Constant(1.0)*meas)
def exit_times(tau):
Tmin = tau(xnear)
Tmax = tau(xfar)
Tavg = avg(tau, geo.dS("moleculeb"))
return (Tmin, Tavg, Tmax)
print
print "--- STATISTICS FOR F=0"
etp_noF = LinearPDE(geo, ExitTimeProblem, phys, F=Constant((0.0,0.0,0.0)))
etp_noF.solve(verbose=False)
T_noF = exit_times(etp_noF.solution)
print "\nTime [s] to reach bottom from molecule for F=0: (min, avg, max)"
print T_noF
print "\nTime [s] to reach bottom from pore entrance for F=0:"
print etp_noF.solution([0.,0.,-3.])
dt = 1e-4
survival = TransientLinearPDE(SurvivalProblem, geo, phys, dt=dt, F=Constant((0.,0.,0.)))
survival.solve(t=T_noF[1], visualize=True, verbose=False)
p = survival.solution
print "After mean time (%s s) to reach bottom from molecule:" %T_noF[1]
for domain in ["pore", "poretop", "porecenter", "porebottom", "fluid_bulk_top", "fluid_bulk_bottom"]:
print "Average survival rate in %s: %.3f percent"%(domain,
100.*assemble(p*geo.dx(domain))/assemble(Constant(1.0)*geo.dx(domain)))
#print "Physics:"
#for item in phys.__dict__.items():
# print "%s = %s" %item
print
print "--- CALCULATING F from PNPS"
print
pde = PNPS(geo, phys)
pde.solve()
#pde.print_results()
(v, cp, cm, u, p) = pde.solutions(deepcopy=True)
F = phys.Feff(v, u)
for domain in ["pore", "poretop", "porecenter", "porebottom", "fluid_bulk_top", "fluid_bulk_bottom"]:
print "Average F in %s:"%domain, assemble(F[2]*geo.dx(domain))/assemble(Constant(1.0)*geo.dx(domain))
#VV = VectorFunctionSpace(geo.mesh, "CG", 1)
#F = project(F, VV)
# solve exit time problem
print
print "--- STATISTICS FOR F=F"
etp = LinearPDE(geo, ExitTimeProblem, phys, F=F)
etp.solve(verbose=False)
T = exit_times(etp.solution)
print "\nTime [s] to reach bottom from molecule: (min, avg, max)"
print T
print "\nTime [s] to reach bottom from pore entrance:"
print etp.solution([0.,0.,-3.])
#plot(F, title="F")
#etp.visualize("exittime")
# TIMESTEP
dt = 1e-5
survival = TransientLinearPDE(SurvivalProblem, geo, phys, dt=dt, F=F)
survival.solve(t=T[1], visualize=True, verbose=False)
p = survival.solution
print "After mean time (%s s) to reach bottom from molecule:" %T[1]
for domain in ["pore", "poretop", "porecenter", "porebottom", "fluid_bulk_top", "fluid_bulk_bottom"]:
print "Average survival rate in %s: %.3f percent"%(domain,
100.*assemble(p*geo.dx(domain))/assemble(Constant(1.0)*geo.dx(domain)))
#interactive()
| mit |
katzenpapst/amunra | src/main/java/de/katzenpapst/amunra/mob/model/ModelRobotVillager.java | 7808 | package de.katzenpapst.amunra.mob.model;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.ModelVillager;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
public class ModelRobotVillager extends ModelVillager
{
ModelRenderer rightArm;
ModelRenderer leftArm;
//ModelRenderer visor;
float ticks = 0;
int curVisorPhase = 0;
public ModelRobotVillager(float par1)
{
this(par1, 0.0F, 64, 64);
}
public ModelRobotVillager(float scaleOrSo, float par2, int textureX, int textureY)
{
super(scaleOrSo, par2, 0, 0);
this.villagerHead = new ModelRenderer(this).setTextureSize(textureX, textureY);
this.villagerHead.setRotationPoint(0.0F, -1.5F + par2, 0.0F);
this.villagerHead.setTextureOffset(0, 0).addBox(-4.0F, -10.0F, -4.0F, 8, 10, 8, scaleOrSo + 0.001F);
// I'll abuse it as the neck
this.villagerNose = new ModelRenderer(this).setTextureSize(textureX, textureY);
this.villagerNose.setRotationPoint(0.0F, par2 - 1.0F, 0.0F);
this.villagerNose.setTextureOffset(24, 0).addBox(-1.0F, -1.0F, -1.0F, 2, 4, 2, scaleOrSo + 0.002F);
/*visor = new ModelRenderer(this).setTextureSize(textureX, textureY);
visor.setRotationPoint(0.0F, par2 - 4.0F, 0.0F);
visor.setTextureOffset(40, 0).addBox(-4.0F, -1.5F, -5.0F, 8, 3, 0, scaleOrSo);
villagerHead.addChild(visor);*/
//this.villagerHead.addChild(this.villagerNose);
this.villagerBody = new ModelRenderer(this).setTextureSize(textureX, textureY);
this.villagerBody.setRotationPoint(0.0F, 0.0F + par2, 0.0F);
this.villagerBody.setTextureOffset(16, 20).addBox(-4.0F, 0.0F, -3.0F, 8, 12, 6, scaleOrSo + 0.003F);
this.villagerBody.setTextureOffset(0, 38).addBox(-4.0F, 0.0F, -3.0F, 8, 18, 6, scaleOrSo + 0.5F + 0.004F);
this.villagerBody.addChild(villagerNose);
/*this.villagerArms = new ModelRenderer(this).setTextureSize(textureX, textureY);
this.villagerArms.setRotationPoint(0.0F, 0.0F + par2 + 2.0F, 0.0F);
this.villagerArms.setTextureOffset(44, 22).addBox(-8.0F, -2.0F, -2.0F, 4, 8, 4, scaleOrSo + 0.005F);
this.villagerArms.setTextureOffset(44, 22).addBox(4.0F, -2.0F, -2.0F, 4, 8, 4, scaleOrSo + 0.0001F);
this.villagerArms.setTextureOffset(40, 38).addBox(-4.0F, 2.0F, -2.0F, 8, 4, 4, scaleOrSo + 0.0004F);*/
this.rightVillagerLeg = new ModelRenderer(this, 0, 22).setTextureSize(textureX, textureY);
this.rightVillagerLeg.setRotationPoint(-2.0F, 12.0F + par2, 0.0F);
this.rightVillagerLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, scaleOrSo + 0.0006F);
this.leftVillagerLeg = new ModelRenderer(this, 0, 22).setTextureSize(textureX, textureY);
this.leftVillagerLeg.mirror = true;
this.leftVillagerLeg.setRotationPoint(2.0F, 12.0F + par2, 0.0F);
this.leftVillagerLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, scaleOrSo + 0.0002F);
rightArm = generateArm(scaleOrSo, par2, textureX, textureY, false);
leftArm = generateArm(scaleOrSo, par2, textureX, textureY, true);
}
private ModelRenderer generateArm(float scaleOrSo, float par2, int textureX, int textureY, boolean mirror) {
float factor = 1.0F;
if(mirror) {
factor = -1.0F;
}
ModelRenderer arm = new ModelRenderer(this).setTextureSize(textureX, textureY);
arm.setRotationPoint(-5.5F*factor, 0.5F + par2, 0.0F);
arm.setTextureOffset(40, 38).addBox(-1.5F, 0.0F, -1.5F,
3, 9, 3, scaleOrSo + 0.004F);
// arm.rotateAngleX = -(float) (Math.PI/4);
arm.mirror = mirror;
ModelRenderer clawFrontUpper = new ModelRenderer(this).setTextureSize(textureX, textureY);
clawFrontUpper.setRotationPoint(0, 8.5F, -1.0F);
clawFrontUpper.setTextureOffset(40, 50).addBox(
-0.5F, 0.5F, -0.5F,
1, 2, 1, scaleOrSo + 0.004F
);
clawFrontUpper.rotateAngleX = -(float)Math.PI / 4;
ModelRenderer clawBackUpper = new ModelRenderer(this).setTextureSize(textureX, textureY);
clawBackUpper.setRotationPoint(0, 8.5F, 1.0F);
clawBackUpper.setTextureOffset(40, 50).addBox(
-0.5F, 0.5F, -0.5F,
1, 2, 1, scaleOrSo + 0.004F
);
clawBackUpper.rotateAngleX = (float)Math.PI / 4;
ModelRenderer clawFrontLower = new ModelRenderer(this).setTextureSize(textureX, textureY);
clawFrontLower.setRotationPoint(0.0F, 9.5F, 3.0F);
clawFrontLower.setTextureOffset(40, 50).addBox(
-0.5F, 0.5F, -0.5F,
1, 2, 1, scaleOrSo + 0.004F
);
clawFrontLower.rotateAngleX = -(float)Math.PI / 4;
ModelRenderer clawBackLower = new ModelRenderer(this).setTextureSize(textureX, textureY);
clawBackLower.setRotationPoint(0.0F, 9.5F, -3.0F);
clawBackLower.setTextureOffset(40, 50).addBox(
-0.5F, 0.5F, -0.5F,
1, 2, 1, scaleOrSo + 0.004F
);
clawBackLower.rotateAngleX = (float)Math.PI / 4;
arm.addChild(clawFrontUpper);
arm.addChild(clawFrontLower);
arm.addChild(clawBackUpper);
arm.addChild(clawBackLower);
return arm;
}
/**
* Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms
* and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how
* "far" arms and legs can swing at most.
*/
@Override
public void setRotationAngles(float time, float walkSpeed, float appendageRotation, float rotationYaw, float rotationPitch, float scale, Entity p_78087_7_)
{
this.villagerHead.rotateAngleY = rotationYaw / (180F / (float)Math.PI);
this.villagerHead.rotateAngleX = rotationPitch / (180F / (float)Math.PI);
/*this.villagerArms.rotationPointY = 3.0F;
this.villagerArms.rotationPointZ = -1.0F;
this.villagerArms.rotateAngleX = -0.75F;*/
this.rightVillagerLeg.rotateAngleX = MathHelper.cos(time * 0.6662F) * 1.4F * walkSpeed * 0.5F;
this.leftVillagerLeg.rotateAngleX = MathHelper.cos(time * 0.6662F + (float)Math.PI) * 1.4F * walkSpeed * 0.5F;
this.rightVillagerLeg.rotateAngleY = 0.0F;
this.leftVillagerLeg.rotateAngleY = 0.0F;
}
/**
* Sets the models various rotation angles then renders the model.
*/
@Override
public void render(Entity curEntity, float timeOrSo, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_)
{
this.setRotationAngles(timeOrSo, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_, curEntity);
//animateVisor(timeOrSo);
this.villagerHead.render(p_78088_7_);
this.villagerBody.render(p_78088_7_);
this.rightVillagerLeg.render(p_78088_7_);
this.leftVillagerLeg.render(p_78088_7_);
//this.villagerArms.render(p_78088_7_);
rightArm.render(p_78088_7_);
leftArm.render(p_78088_7_);
}
/*private void animateVisor(float partialTicks) {
ticks += partialTicks;
if(ticks > 12) {
ticks = ticks - ((int)(ticks/12))*12;
}
int yOffset = (int)(ticks);
if(curVisorPhase != yOffset) {
curVisorPhase = yOffset;
// update rendering
if(curVisorPhase < 6) {
visor.setTextureOffset(40, curVisorPhase*3);
} else {
visor.setTextureOffset(40, (6-curVisorPhase)*3);
}
}
//if(ticks <= 0) {
// visor.setTextureOffset(40, 0);
//}
}*/
} | mit |
dg9ngf/MultiSelectTreeView | MultiSelectTreeView.Test/Model/Element.cs | 2076 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using MultiSelectTreeView.Test.Model.Helper;
namespace MultiSelectTreeView.Test.Model
{
class Element
{
public Element(AutomationElement automationElement)
{
Ae = automationElement;
}
internal AutomationElement Ae { get; private set; }
public void Expand()
{
ExpandCollapsePattern expandPattern = Ae.GetPattern<ExpandCollapsePattern>();
expandPattern.Expand();
}
public void Collapse()
{
ExpandCollapsePattern expandPattern = Ae.GetPattern<ExpandCollapsePattern>();
expandPattern.Collapse();
}
public void Select()
{
SelectionItemPattern pattern = Ae.GetPattern<SelectionItemPattern>();
pattern.Select();
}
public bool IsSelected
{
get
{
SelectionItemPattern pattern = Ae.GetPattern<SelectionItemPattern>();
return pattern.Current.IsSelected;
}
}
public bool IsExpanded
{
get
{
ExpandCollapsePattern pattern = Ae.GetPattern<ExpandCollapsePattern>();
return pattern.Current.ExpandCollapseState == ExpandCollapseState.Expanded;
}
}
public bool IsFocused
{
get
{
return Convert.ToBoolean(GetValue("node;IsFocused"));
}
}
public bool IsSelectedPreview
{
get
{
return Convert.ToBoolean(GetValue("node;IsSelectedPreview"));
}
}
public string GetValue(string id)
{
ValuePattern pattern = Ae.GetPattern<ValuePattern>();
pattern.SetValue(id);
return pattern.Current.Value;
}
}
}
| mit |
AliBrahem/AfrikIsol | src/BackOffice/AdminBundle/Controller/UserController.php | 9038 | <?php
namespace BackOffice\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use BackOffice\AdminBundle\Form\UserType;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\FOSUserBundle;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Ob\HighchartsBundle\Highcharts\Highchart;
class UserController extends Controller
{
public function indexAction()
{
return $this->render('AdminBundle:Default:index.html.twig'
);
}
public function showAction()
{
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('AdminBundle:User:showProfile.html.twig', array(
'user' => $user
));
}
public function updateAction(Request $request) {
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('AdminBundle:User:updateProfile.html.twig', array(
'form' => $form->createView()
));
}
public function listerAction() {
$query = $this->getDoctrine()->getEntityManager()
->createQuery(
'SELECT u FROM AdminBundle:User u WHERE u.roles NOT LIKE :role'
)->setParameter('role', '%"ROLE_ADMIN"%');
$users = $query->getResult();
return $this->render('AdminBundle:User:list.html.twig', array('users' => $users));
}
public function updateOtherAction($id)
{
$em = $this->container->get('doctrine')->getEntityManager();
$entity = $em->getRepository('AdminBundle:User')->find($id);
$form = $this->createFormBuilder($entity)
->add('Username')
->add('Email')
->add('Roles', 'collection',
array('label' => false,
'type' => 'choice',
'options' => array( 'choices'
=> array('ROLE_TECHNIQUE' => 'Service Technique',
'ROLE_COMMERCIAL' => 'Service Commercial',
'ROLE_LOGISTIQUE' => 'Service Logistique',
'ROLE_FINANCIER' => 'Service Financier',''=>''), 'empty_value' => 'Choisissez le poste',
'empty_data' => null ) ))
->add('Locked', 'choice', array(
'choices' => array('0' => 'Activer', '1' => 'Désactiver'),
'required' => true))
->add('ExpiresAt', 'datetime')
->getForm();
$form->setData($entity);
$request = $this->getRequest();
//verifie si le formulaire est submitter puis il récupère les données de la requête si la requête est porteuxe des données
if ($form->handleRequest($request)->isValid()) {
$objToPersist = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($objToPersist);
$em->flush();
// $userManager = $this->get('fos_user.user_manager');
// $users = $userManager->findUsers();
$query = $this->getDoctrine()->getEntityManager()
->createQuery(
'SELECT u FROM AdminBundle:User u WHERE u.roles NOT LIKE :role'
)->setParameter('role', '%"ROLE_ADMIN"%');
$users = $query->getResult();
return $this->render('AdminBundle:User:list.html.twig', array('users' => $users));
}
return $this->render('AdminBundle:User:updateOtherUser.html.twig',array(
'form' => $form->createView(),'id'=> $id
));
}
public function deleteAction($id) {
$em = $this->container->get('doctrine')->getEntityManager();
$entity = $em->getRepository('AdminBundle:User')->find($id);
$em->remove($entity);
$em->flush();
$userManager = $this->get('fos_user.user_manager');
$users = $userManager->findUsers();
return $this->render('AdminBundle:User:list.html.twig', array('users' => $users));
}
public function chartLineAction($id){
$em = $this->container->get('doctrine')->getEntityManager();
$modele = $em->getRepository('AdminBundle:Projet')->find($id);
$plan = $em->getRepository('AdminBundle:Avancement')->findOneBy(array('idprojet' => $id));
return $this->render('AdminBundle:User:LineChart.html.twig', array(
'plan'=>$plan
));
}
public function chartGanttAction($id){
$em = $this->container->get('doctrine')->getEntityManager();
$modele = $em->getRepository('AdminBundle:Projet')->find($id);
$plan = $em->getRepository('AdminBundle:Gantt')->findBy(array('idprojet' => $id));
return $this->render('AdminBundle:User:gantt.html.twig', array(
'plan'=>$plan,'projet'=>$modele
));
}
public function chartGanttJAction($id){
$em = $this->container->get('doctrine')->getEntityManager();
$modele = $em->getRepository('AdminBundle:Projet')->find($id);
$plan = $em->getRepository('AdminBundle:Gantt2')->findBy(array('idprojet' => $id));
return $this->render('AdminBundle:User:ganttJ.html.twig', array(
'plan'=>$plan,'projet'=>$modele
));
}
public function suivieChartAction($id){
$em = $this->container->get('doctrine')->getEntityManager();
$modele = $em->getRepository('AdminBundle:Projet')->find($id);
$query = $em->createQuery(
'SELECT p
FROM AdminBundle:Avancement p
WHERE p.idprojet = :id
ORDER BY p.date ASC')
->setParameter('id', $id);
$avanc = $query->getResult();
//$avanc = $em->getRepository('AdminBundle:Avancement')->findBy(array('idprojet' => $id));
$query2 = $em->createQuery(
'SELECT p
FROM AdminBundle:MAD p
WHERE p.idprojet = :id
ORDER BY p.date ASC')
->setParameter('id', $id);
$mad = $query2->getResult();
// $mad = $em->getRepository('AdminBundle:MAD')->findBy(array('idprojet' => $id));
$query3 = $em->createQuery(
'SELECT p
FROM AdminBundle:Planification p
WHERE p.idprojet = :id
ORDER BY p.date ASC')
->setParameter('id', $id);
$plan = $query3->getResult();
//$plan = $em->getRepository('AdminBundle:Planification')->findBy(array('idprojet' => $id));
return $this->render('AdminBundle:User:suivieChart.html.twig', array(
'avanc'=>$avanc,'projet'=>$modele,'mad'=>$mad,'plan'=>$plan,'id'=>$id
));
}
} | mit |
schmurfy/get_them_all | lib/get_them_all/site_downloader.rb | 13044 |
require 'fiber'
require 'addressable/uri'
require 'active_support/hash_with_indifferent_access'
require 'em-http-request'
require 'em-priority-queue'
module GetThemAll
##
# The main class, all your crawlers will derive from this class
# see examples/standalone.rb file for an example.
#
class SiteDownloader
include Notifier
# number of worker for each tasks
class_attribute :examiners_count, :downloaders_count
# delay between each action for one worker
class_attribute :examiners_delay, :downloaders_delay
self.examiners_count = 1
self.downloaders_count = 1
# default: 100 to 200ms between actions
self.downloaders_delay = [100, 200]
self.examiners_delay = [100, 200]
##
# Determine what will be stored in the history file,
# the default is to store the last url before the download
# so we can ignore it sooner next time.
#
# The other mode is :download, in this mode the download
# url itself will be stored, it is meant for special cases as
# the default should work better most of the time.
#
class_attribute :history_tracking
self.history_tracking = :default
attr_reader :base_url, :storage, :history, :state
##
# If true a new filename will be generated for every file
# for which the destination already exists
attr_reader :rename_duplicates
##
# Create and start the crawler.
#
# @param [Hash] args arguments
# @option args [String] :base_url The root url, every other
# url will be relative to this.
# @option args [String] :start_url What is the very first url
# to examine (level 0) relative to base_url, default is "/"
# @option args [String] :folder_name The root path where
# downloaded files will be saved (appended to the storage root).
# @option args [Array] :extensions Array of Extension object.
# @option args [Boolean] :rename_duplicates If true a new name will be
# generated if the file exists.
#
# @option args [Hash] :storage Configure storage backend
# :type is the backend name
# :params is a hash with backend specific options
#
def initialize(args)
@cookies = []
@history = []
@connections = {}
@examine_queue = EM::PriorityQueue.new
@download_queue = EM::PriorityQueue.new
@history = History.new
@state = :stopped
@base_url= args.delete(:base_url)
@start_urls = args.delete(:start_urls) || ['/']
@folder_name= args.delete(:folder_name)
@login_request = args.delete(:login_request)
@rename_duplicates = args.delete(:rename_duplicates)
# keep a pointer to each extension
@extensions = args.delete(:extensions) || [ActionLogger]
storage_options = args.delete(:storage)
raise "storage required" unless storage_options
raise "storage type required" unless storage_options[:type]
raise "storage params required" unless storage_options[:params]
storage_class = "#{storage_options[:type].camelize}Storage"
raise "unknown storage: #{storage_class}" unless defined?(storage_class)
storage_class = GetThemAll.const_get(storage_class)
storage_class = storage_class
storage_options = ActiveSupport::HashWithIndifferentAccess.new( storage_options[:params] )
@storage = storage_class.new(storage_options.merge(:folder_name => @folder_name))
@parsed_base_url = Addressable::URI.parse(@base_url)
# start_url is relative to base_url
@start_urls.map!{|path| File.join(@base_url, path) }
# if any unknown option was passed, do not silently walk away
# tell the user !
unless args.empty?
raise "unknown parameters: #{args.inspect}"
end
end
def stopping?
@state == :stopping
end
def running?
@state == :running
end
def stopped?
@state == :stopped
end
##
# Start the crawler, if you pass a block it
# will be called after the engine is iniailized, you can
# queue the level 0 urls here and handle authenticating if needed.
#
def start
load_history()
@state = :running
notify('downloader.started', self)
EM::run do
@exit_timer = EM::add_periodic_timer(2) do
# if all workers are idle
# and there is nothing in queue
# then stop the engine
#
if @examiners.all?(&:idle?) && @downloaders.all?(&:idle?) &&
@examine_queue.empty? && @download_queue.empty?
self.stop()
end
end
EM::error_handler do |err|
if err.is_a?(AssertionFailed)
error("Assertion failed: #{err.message}")
else
error("#{err.class}: #{err.message}")
err.backtrace.each do |line|
error(line)
end
end
end
# authenticate connection if required
if @login_request
open_url(*@login_request) do |req, doc|
after_login()
end
else
after_login()
end
end
notify('downloader.completed', self)
end
def after_login
@start_urls.each do |start_url|
# queue the first action to start crawling
#
@examine_queue.push(ExamineAction.new(self,
:url => start_url,
:destination_folder => '/',
:level => 0
), 0)
end
# now that actions are queued, start handling them
# start each "worker"
# dequeuing is priority based, the download actions
# first and then the higher the level the higher the
# priority for examine actions, this is done this way
# to give work to the download workers asap.
#
@examiners = []
@downloaders = []
1.upto(self.class.examiners_count) do |n|
@examiners << Worker.new(:examiner, n - 1, @examine_queue, self.class.examiners_delay)
end
1.upto(self.class.downloaders_count) do |n|
@downloaders << Worker.new(:downloader, n - 1, @download_queue, self.class.downloaders_delay)
end
end
##
# Cleanly stop the engine and ensure the history file is
# written.
#
def stop(&block)
return if stopping?
# first stop the exit timer, no longer needed once we are here
@exit_timer.cancel()
@state = :stopping
Fiber.new do
fiber = Fiber.current
notify('downloader.stopping', self)
# first ask every workers to stop their work
# starting with examiners
@examiners.each do |worker|
debug "Stopping Examiner #{worker.index}..."
worker.request_stop { fiber.resume }
Fiber.yield
debug "Stopped Examiner #{worker.index}"
end
@downloaders.each do |worker|
debug "Stopping Downloader #{worker.index}..."
worker.request_stop { fiber.resume }
Fiber.yield
debug "Stopped Downloader #{worker.index}"
end
# now that every worker is stopped, write the history
deferrable = save_history()
deferrable.callback{ fiber.resume }
Fiber.yield
@state = :stopped
notify('downloader.stopped', self)
block.call if block
end.resume
end
class AssertionFailed < RuntimeError; end
def assert(cond, msg = "")
unless cond
raise AssertionFailed, msg
end
end
# toto.com
# sub.toto.com
##
# Check if two urls are from the same domain.
#
# @return [Boolean] true if same domain
#
def same_domain?(host1, host2)
host1_parts = host1.split(".")
host2_parts = host2.split(".")
size = [host1_parts.size, host2_parts.size].min # => 2
host1_parts= host1_parts[-size..-1] if host1_parts.size > size
host2_parts= host2_parts[-size..-1] if host2_parts.size > size
ret = host1_parts.join(".") == host2_parts.join(".")
return ret
end
HISTORY_FILE_PATH = 'history.txt'.freeze
# load already downloaded pictures from disk
def load_history
if @storage.exist?(HISTORY_FILE_PATH)
data = @storage.read(HISTORY_FILE_PATH)
@history.load(data)
else
debug "History file not found: #{HISTORY_FILE_PATH}"
end
end
def save_history
@storage.write(HISTORY_FILE_PATH, @history.dump)
end
# Plugin API
def open_url(url, method = "GET", params = nil, referer = nil, deferrable = nil, &block)
deferrable ||= EM::DefaultDeferrable.new
referer ||= @base_url
url = Addressable::URI.parse( (url[0...4] == "http") ? url : URI.join(@base_url, url) )
# url = (url[0...4] == "http") ? URI.parse(url) : URI.join(@base_url, url)
# url_path = url.path
# get queries with params
# if method == "GET" && url.query
# url_path << "?#{url.query}"
# end
external = !same_domain?(@parsed_base_url.host, url.host)
if external
debug("Opening external page: #{url}")
else
# debugger if url.to_s == "http://fan tasti.cc/user/pussylover75/images/image/367771"
debug("#{method.upcase} #{url}")
end
# find a connection for this host
host_key = "#{url.host}:#{url.port}"
if false
# if @connections.has_key?(host_key) && !@connections[host_key].error?
http = @connections[host_key]
else
# debug("New connection to http://#{url.host}:#{url.port}", "C")
http = EM::HttpRequest.new("http://#{url.host}:#{url.port}")
@connections[host_key] = http
end
req = http.setup_request(method.downcase.to_sym,
:path => url.path,
:query => url.query,
# :redirects => 2,
:head => {
:cookie => @cookies,
:referer => referer,
# "accept-encoding" => "gzip, compressed",
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1'
}
)
# req.timeout(10)
# req.errback do
# error("error while opening #{url} :(")
# end
req.callback do
case req.response_header.status
when 200
# handle cookies
unless external
# [["a=42", "PHPSESSID2=u0ctlbfrlrnus1qv8425uv4p42"], ["PHPSESSID=2jek8d61dlt134e0djft4hnn54; path=/", "OAGEO=FR%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C; path=/", "OAID=924ff65ed90c7834d8b37b29bdffc831; expires=Sun, 14-Oct-2012 12:22:22 GMT; path=/", "OAID=924ff65ed90c7834d8b37b29bdffc831; expires=Sun, 14-Oct-2012 12:22:22 GMT; path=/", "OAID=924ff65ed90c7834d8b37b29bdffc831; expires=Sun, 14-Oct-2012 12:22:22 GMT; path=/"]]
# [["a=42"], "PHPSESSID=p12aet71oemrfb3olffqaptss3; path=/"]
added_cookies = Array(req.cookies[1])
added_cookies.each do |str|
@cookies << str.split(';').first
end
# remove duplicates
@cookies.uniq!
# req.added_cookies.each{|key,val| @cookies[key] = val }
# req.deleted_cookies.each{|key, _| @cookies.delete(key) }
end
# debug("page loaded succesfully: #{url}")
deferrable.set_deferred_status(:succeeded, req)
if block
if block.arity == 2
doc = Hpricot(req.response)
block.call(req, doc)
else
block.call(req)
end
end
# em-http-request does not handle redirection between hosts
# so handle them ourselves
when 301, 302
location = req.response_header.location
if location
debug("Following redirection: #{location}")
# reuse the same deferrable object
open_url(location, method, params, referer, deferrable, &block)
end
else
puts "#{method} #{url} => Status: #{req.response_header.status}"
deferrable.set_deferred_status(:failed, req.response_header.http_reason)
end
end
req.errback do
deferrable.set_deferred_status(:failed, -1)
end
deferrable
end
def eval_javascript(data)
JavascriptLoader.new(data)
end
# to be redefine in subclasses
def examine_page(doc, level)
raise "Need to implement examine_page in #{self.class}"
end
def get_file_destpath_from_action(action)
url_folder = action.uri.path
File.join(action.destination_folder, url_folder)
end
end
end
| mit |
gubaojian/trylearn | WebLayoutCore/Source/WebCore/platform/network/cf/CredentialStorageCFNet.cpp | 2312 | /*
* Copyright (C) 2009 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#include "config.h"
#include "CredentialStorage.h"
#if USE(CFURLCONNECTION)
#include "AuthenticationCF.h"
#include "Credential.h"
#include "ProtectionSpace.h"
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#include <pal/spi/cf/CFNetworkSPI.h>
#include <wtf/RetainPtr.h>
namespace WebCore {
static inline CFURLCredentialRef copyCredentialFromProtectionSpace(CFURLProtectionSpaceRef protectionSpace)
{
auto storage = adoptCF(CFURLCredentialStorageCreate(kCFAllocatorDefault));
return CFURLCredentialStorageCopyDefaultCredentialForProtectionSpace(storage.get(), protectionSpace);
}
Credential CredentialStorage::getFromPersistentStorage(const ProtectionSpace& protectionSpace)
{
auto protectionSpaceCF = adoptCF(createCF(protectionSpace));
auto credentialCF = adoptCF(copyCredentialFromProtectionSpace(protectionSpaceCF.get()));
return core(credentialCF.get());
}
} // namespace WebCore
#endif // USE(CFURLCONNECTION)
| mit |
y-takano/Foca | main/java/jp/gr/java_conf/ke/foca/LoggerThreadService.java | 3660 | package jp.gr.java_conf.ke.foca;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import jp.gr.java_conf.ke.foca.annotation.Logger;
import jp.gr.java_conf.ke.util.Reflection;
import jp.gr.java_conf.ke.namespace.foca.LogLevel;
/**
* Created by YT on 2017/04/21.
*/
class LoggerThreadService {
private static final String LOGGER_THREAD_NAME = "Foca-LoggerThread";
private static final String DEFAULT_LOGGER_NAME = "DEFAULT";
private static final BlockingQueue<LoggingInterface> queue =
new ArrayBlockingQueue<LoggingInterface>(1000, true);
private Thread thread;
LoggerThreadService() {
thread = new Thread(new Runnable() {
public void run() {
try {
while (true) {
queue.take().invoke();
}
} catch (InterruptedException e) {
} catch (Throwable th) {
th.printStackTrace();
run();
}
}
});
thread.setDaemon(true);
thread.setName(LOGGER_THREAD_NAME);
thread.start();
}
Logger createLogger(jp.gr.java_conf.ke.namespace.foca.Logger xmlElement) throws FocaException {
Logger instance = Reflection.newInstance(xmlElement.getClazz(), Logger.class);
InvocationHandler handler = new LoggerProxy(xmlElement.getLevel(), instance);
return (Logger) Proxy.newProxyInstance(
instance.getClass().getClassLoader(),
new Class[] {Logger.class},
handler);
}
static String defaultLoggerName() {
return DEFAULT_LOGGER_NAME;
}
private static final class LoggerProxy implements InvocationHandler {
private LogLevel level;
private Logger logger;
LoggerProxy(LogLevel level, Logger logger) {
this.level = level;
this.logger = logger;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().startsWith("getLevel")) {
switch (level) {
case ERROR:
return Logger.Level.ERROR;
case INFO:
return Logger.Level.INFO;
case TRACE:
return Logger.Level.TRACE;
case DEBUG:
default:
return Logger.Level.DEBUG;
}
}
switch (level) {
case ERROR:
if (method.getName().equals("info")) return null;
case INFO:
if (method.getName().equals("trace")) return null;
case TRACE:
if (method.getName().equals("debug")) return null;
case DEBUG:
default:
break;
}
LoggingInterface logBean = new LoggingInterface(logger, method, args);
queue.put(logBean);
return null;
}
}
private static class LoggingInterface {
private Object proxy;
private Method method;
private Object[] args;
LoggingInterface(Object proxy, Method method, Object[] args) {
this.proxy = proxy;
this.method = method;
this.args = args;
}
void invoke() throws Throwable {
method.invoke(proxy, args);
}
}
}
| mit |
cclaiborne/qasite | config/environment.rb | 152 | # Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Qasite::Application.initialize!
| mit |
clux/ffa-tb | test/readme.test.js | 3043 | var FfaTb = require('..')
, FFA = require('ffa')
, fId = (r, m) => new FFA.Id(r, m)
, TB = require('tiebreaker')
, tbId = (s) => new TB.Id(s, 1, 1, true)
, test = require('bandage');
test('readme', function *(t) {
var trn = new FfaTb(16, { sizes: [4, 4, 4], advancers: [2, 2], limit: 2 });
// round 1 - quarter finals
trn.inFFA(); // true
t.eq(trn.matches, [
{ id: fId(1, 1), p: [ 1, 5, 12, 16 ] },
{ id: fId(1, 2), p: [ 2, 6, 11, 15 ] },
{ id: fId(1, 3), p: [ 3, 7, 10, 14 ] },
{ id: fId(1, 4), p: [ 4, 8, 9, 13 ] } ],
'round one is ffa quarter finals'
);
trn.matches.forEach(m => {
trn.score(m.id, m.id.m === 3 ? [4,3,3,1]: [4,3,2,1]); // tie match 3
});
t.ok(trn.stageDone(), 'ffa round 1 has been played (but there were ties)');
t.false(trn.isDone(), 'have two more ffa rounds to go');
t.ok(trn.createNextStage(), 'must createNextStage when stageDone && !isDone');
// tiebreakers for R1
t.ok(trn.inTieBreaker() && !trn.inFinal(), 'in R1 tiebreaker');
t.eq(trn.matches, [
{ id: tbId(3), p: [ 7, 10 ] } ],
'tiebreaking only 2 players from match 3'
);
trn.score(trn.matches[0].id, [0,1]);
t.ok(trn.stageDone() && !trn.isDone(), 'only stage done so far');
t.ok(trn.createNextStage(), 'intermediate tiebreaker stage over');
// round 2 - semifinals
t.ok(trn.inFFA() && !trn.inFinal(), 'ffa round 2');
t.eq(trn.matches, [
{ id: fId(1, 1), p: [ 1, 3, 6, 10 ] },
{ id: fId(1, 2), p: [ 2, 4, 5, 8 ] } ],
'round 2 are the semis'
);
trn.matches.forEach(m => {
trn.score(m.id, [4,3,2,1]); // score without ties
});
t.ok(trn.stageDone() && !trn.isDone(), 'only two stages done so far');
t.ok(trn.createNextStage(), 'advance to round 3');
// round 3
t.ok(trn.inFFA() && trn.inFinal(), 'straight into final round after fast R2');
t.eq(trn.matches, [
{ id: fId(1, 1), p: [ 1, 2, 3, 4 ] } ],
'final has top 4'
);
t.ok(trn.score(trn.matches[0].id, [1,1,1,1]), 'complete tie in final');
t.ok(trn.stageDone() && !trn.isDone(), 'need to tiebreak final (limit set to 2)');
t.ok(trn.createNextStage(), 'generate tiebreakers for final limit');
// tiebreaker for final
t.ok(trn.inTieBreaker() && trn.inFinal(), 'still in final, but in a tiebreaker round');
t.eq(trn.matches, [
{ id: tbId(1), p: [ 1, 2, 3, 4 ] } ],
'mtach is a complete replay of final'
);
t.ok(trn.score(trn.matches[0].id, [1,1,1,0]), 'tie slightly less');
t.ok(trn.stageDone() && !trn.isDone(), 'need to tiebreak final better');
t.ok(trn.createNextStage(), 'create another tiebreakers for final limit');
// tiebreaker for final again
t.ok(trn.inTieBreaker() && trn.inFinal(), 'still in final and in tiebreaker');
t.eq(trn.matches, [
{ id: tbId(1), p: [ 1, 2, 3 ] } ],
'tiebreaker final has one less player'
);
t.ok(trn.score(trn.matches[0].id, [1,1,0]), 'tied for 1st place');
t.ok(trn.stageDone() && trn.isDone(), 'we do not need to break the top 2');
trn.complete(); // can lock down the tourney now.
});
| mit |
Berna93/SiteRubi | pages/cursoParticipantes.php | 6348 | <?php
include('session.php');
?>
<?php require_once 'config.php'; ?>
<?php require_once DBAPI; ?>
<?php
require_once('cursos/functions.php');
searchCourseStudents($curso['id']);
editParticipant();
?>
<?php include(HEADER_TEMPLATE); ?>
<?php $db = open_database(); ?>
<?php if ($db) : ?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Cadastro de Cursos</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="col-lg-12" align="right">
<a href="download.php" class="btn btn-sm btn-primary"><i class="fa fa-download"></i> Download</a>
</div>
<div>
<br><br><br>
<?php if (!empty($_SESSION['message'])) : ?>
<div class="alert alert-<?php echo $_SESSION['type']; ?> alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $_SESSION['message']; ?>
</div>
<?php endif; ?>
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Dados básicos
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<form role="form" action="cursoParticipantes.php?id=<?php echo $curso['id']; ?>" method="post">
<div class="form-group">
<label>Nome do Curso</label>
<input type="text" class="form-control" readonly name="curso['nome']" value="<?php echo $curso['nome']; ?>">
<label>Professor/Palestrante</label>
<input type="text" class="form-control" readonly name="curso['professor']" value="<?php echo $curso['professor']; ?>">
<label>Quantidade de Vagas</label>
<input type="text" class="form-control" readonly name="curso['qtdeVagas']" value="<?php echo $curso['qtdeVagas']; ?>">
<p class="help-block">Apenas números</p>
<label>Adicionar Participante</label>
<div class="form-group input-group">
<input type="text" class="form-control" id="skills" name="participante['nomeCliente']"/>
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="btnAdiciona"><i class="fa fa-check"></i>
</button>
</span>
</div>
</div>
</form>
</div>
<div class="col-lg-6">
<div>
<p>
<strong>Preenchimento das Vagas</strong>
<span class="pull-right text-muted"><?php echo ($curso['qtdePreenchidas']/$curso['qtdeVagas'] * 100) . "% Completo"; ?></span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="<?php echo ($curso['qtdePreenchidas']/$curso['qtdeVagas'] * 100); ?>" aria-valuemin="0" aria-valuemax="100" style="<?php echo "width:" . ($curso['qtdePreenchidas']/$curso['qtdeVagas'] * 100) . "%"; ?>">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</div>
<div class="panel-heading">
Participantes
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Situação Financeira</th>
<th>Excluir Participante</th>
<th>Baixar Contrato</th>
</tr>
</thead>
<tbody>
<?php if ($cursosParticipantes) : ?>
<?php foreach ($cursosParticipantes as $participante) : ?>
<tr>
<td><?php echo $participante['id']; ?></td>
<td><?php echo $participante['nomeCliente']; ?></td>
<td class="center">
<a href="#" class="btn btn-success btn-circle" data-toggle="modal" data-target="#delete-modal-participante" data-customer="<?php echo $participante['id']; ?>" data-curso="<?php echo $curso['id']; ?>"><i class="fa fa-dollar">
</td>
<td class="center">
<a href="#" class="btn btn-warning btn-circle <?php if ($_SESSION['usertype']!='admin') echo "disabled"; ?>" data-toggle="modal" data-target="#delete-modal-participante" data-customer="<?php echo $participante['id']; ?>" data-curso="<?php echo $curso['id']; ?>"><i class="fa fa-times">
<td><?php echo $participante['situacaoPagamento']; ?></td>
<td class="center">
<a href="edicaoCliente.php?id=<?php echo $customer['id']; ?>" class="btn btn-warning btn-circle"><i class="fa fa-times">
</td>
<td class="center">
<a href="edicaoCliente.php?id=<?php echo $customer['id']; ?>" class="btn btn-info btn-circle"><i class="fa fa-download">
</td>
</tr>
<?php endforeach; ?>
<?php else : ?>
<tr>
<td colspan="6">Nenhum registro encontrado.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
</div>
</div>
</div>
<!-- /.panel-body -->
<button type="submit" class="btn btn-primary">Atualizar</button>
<button type="reset" class="btn btn-warning">Limpar</button>
<a href="#" class="btn btn-danger" data-toggle="modal" data-target="#delete-modal-curso" data-customer="<?php echo $curso['id']; ?>">
<i class="fa fa-trash"></i> Excluir
</a>
</form>
</div>
<!-- /.col-lg-6 (nested) -->
</div>
<!-- /.row (nested) -->
</div>
</div>
</div>
</div>
<?php else : ?>
<div class="alert alert-danger" role="alert">
<p><strong>ERRO:</strong> Não foi possível Conectar ao Banco de Dados!</p>
</div>
<?php endif; ?>
<?php include('cursos/modal.php'); ?>
<?php include('cursos/modalParticipante.php'); ?>
<?php include(FOOTER_TEMPLATE); ?>
| mit |
legendblade/CraftingHarmonics | src/main/java/org/winterblade/minecraft/harmony/mobs/sheds/matchers/temperature/MinTemperatureMatcher.java | 1521 | package org.winterblade.minecraft.harmony.mobs.sheds.matchers.temperature;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import org.winterblade.minecraft.harmony.api.BaseMatchResult;
import org.winterblade.minecraft.harmony.api.Component;
import org.winterblade.minecraft.harmony.api.PrioritizedObject;
import org.winterblade.minecraft.harmony.api.Priority;
import org.winterblade.minecraft.harmony.api.mobs.sheds.IMobShedMatcher;
import org.winterblade.minecraft.harmony.temperature.matchers.BaseTemperatureMatcher;
import javax.annotation.Nullable;
/**
* Created by Matt on 6/6/2016.
*/
@Component(properties = {"temperatureMin", "temperatureProvider" })
@PrioritizedObject(priority = Priority.MEDIUM)
public class MinTemperatureMatcher extends BaseTemperatureMatcher implements IMobShedMatcher {
public MinTemperatureMatcher(double temp) {
this(temp, null);
}
public MinTemperatureMatcher(double temp, @Nullable String provider) {
super(temp, Integer.MAX_VALUE, provider);
}
/**
* Should return true if this matcher matches the given event
*
* @param entityLivingBase The event to match
* @param drop The dropped item; this can be modified.
* @return True if it should match; false otherwise
*/
@Override
public BaseMatchResult isMatch(EntityLivingBase entityLivingBase, ItemStack drop) {
return matches(entityLivingBase.getEntityWorld(), entityLivingBase.getPosition());
}
}
| mit |
Xaiid/ng-bootstrap | accordion/accordion.module.ngfactory.js | 907 | /**
* @fileoverview This file was generated by the Angular template compiler. Do not edit.
*
* @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes}
* tslint:disable
*/
import * as i0 from "@angular/core";
import * as i1 from "./accordion.module";
import * as i2 from "@angular/common";
var NgbAccordionModuleNgFactory = i0.ɵcmf(i1.NgbAccordionModule, [], function (_l) { return i0.ɵmod([i0.ɵmpd(512, i0.ComponentFactoryResolver, i0.ɵCodegenComponentFactoryResolver, [[8, []], [3, i0.ComponentFactoryResolver], i0.NgModuleRef]), i0.ɵmpd(4608, i2.NgLocalization, i2.NgLocaleLocalization, [i0.LOCALE_ID, [2, i2.ɵa]]), i0.ɵmpd(512, i2.CommonModule, i2.CommonModule, []), i0.ɵmpd(512, i1.NgbAccordionModule, i1.NgbAccordionModule, [])]); });
export { NgbAccordionModuleNgFactory as NgbAccordionModuleNgFactory };
//# sourceMappingURL=accordion.module.ngfactory.js.map | mit |
theofidry/alice | tests/Generator/Populator/SimpleHydratorTest.php | 9940 | <?php
/*
* This file is part of the Alice package.
*
* (c) Nelmio <hello@nelm.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Nelmio\Alice\Generator\Hydrator;
use Nelmio\Alice\Definition\Fixture\SimpleFixture;
use Nelmio\Alice\Definition\MethodCallBag;
use Nelmio\Alice\Definition\Object\SimpleObject;
use Nelmio\Alice\Definition\Property;
use Nelmio\Alice\Definition\PropertyBag;
use Nelmio\Alice\Definition\SpecificationBag;
use Nelmio\Alice\Definition\Value\FakeObject;
use Nelmio\Alice\Definition\Value\FakeValue;
use Nelmio\Alice\Throwable\Exception\RootResolutionException;
use Nelmio\Alice\FixtureBag;
use Nelmio\Alice\Generator\GenerationContext;
use Nelmio\Alice\Generator\HydratorInterface;
use Nelmio\Alice\Generator\ResolvedFixtureSet;
use Nelmio\Alice\Generator\ResolvedFixtureSetFactory;
use Nelmio\Alice\Generator\ResolvedValueWithFixtureSet;
use Nelmio\Alice\Generator\Resolver\Value\FakeValueResolver;
use Nelmio\Alice\Generator\ValueResolverInterface;
use Nelmio\Alice\ObjectBag;
use Nelmio\Alice\ParameterBag;
use Nelmio\Alice\Throwable\GenerationThrowable;
use Prophecy\Argument;
/**
* @covers \Nelmio\Alice\Generator\Hydrator\SimpleHydrator
*/
class SimpleHydratorTest extends \PHPUnit_Framework_TestCase
{
public function testIsAnHydrator()
{
$this->assertTrue(is_a(SimpleHydrator::class, HydratorInterface::class, true));
}
public function testIsValueResolverAware()
{
$this->assertEquals(
(new SimpleHydrator(new FakePropertyHydrator()))->withValueResolver(new FakeValueResolver()),
new SimpleHydrator(new FakePropertyHydrator(), new FakeValueResolver())
);
}
/**
* @expectedException \Nelmio\Alice\Throwable\Exception\Generator\Resolver\ResolverNotFoundException
* @expectedExceptionMessage Expected method "Nelmio\Alice\Generator\Hydrator\SimpleHydrator::hydrate" to be called only if it has a resolver.
*/
public function testThrowsAnExceptionIfDoesNotHaveAResolver()
{
$hydrator = new SimpleHydrator(new FakePropertyHydrator());
$hydrator->hydrate(new FakeObject(), ResolvedFixtureSetFactory::create(), new GenerationContext());
}
public function testAddsObjectToFixtureSet()
{
$object = new SimpleObject('dummy', new \stdClass());
$set = ResolvedFixtureSetFactory::create(
null,
$fixtures = (new FixtureBag())->with(
new SimpleFixture(
'dummy',
\stdClass::class,
new SpecificationBag(
null,
new PropertyBag(),
new MethodCallBag()
)
)
)
);
$expected = new ResolvedFixtureSet(
new ParameterBag(),
$fixtures,
new ObjectBag(['dummy' => $object])
);
$hydrator = new SimpleHydrator(new FakePropertyHydrator(), new FakeValueResolver());
$actual = $hydrator->hydrate($object, $set, new GenerationContext());
$this->assertEquals($expected, $actual);
}
public function testHydratesObjectWithTheGivenProperties()
{
$object = new SimpleObject('dummy', new \stdClass());
$set = ResolvedFixtureSetFactory::create(
null,
$fixtures = (new FixtureBag())->with(
new SimpleFixture(
'dummy',
\stdClass::class,
new SpecificationBag(
null,
(new PropertyBag())
->with($username = new Property('username', 'Bob'))
->with($group = new Property('group', 'Badass')),
new MethodCallBag()
)
)
)
);
$context = new GenerationContext();
$context->markIsResolvingFixture('foo');
$hydratorProphecy = $this->prophesize(PropertyHydratorInterface::class);
$newInstance = new \stdClass();
$newInstance->username = 'Bob';
$newObject = $object->withInstance($newInstance);
$hydratorProphecy->hydrate($object, $username, $context)->willReturn($newObject);
$secondNewInstance = clone $newInstance;
$secondNewInstance->group = 'Badass';
$secondNewObject = $object->withInstance($secondNewInstance);
$hydratorProphecy->hydrate($newObject, $group, $context)->willReturn($secondNewObject);
/** @var PropertyHydratorInterface $hydrator */
$hydrator = $hydratorProphecy->reveal();
$expected = new ResolvedFixtureSet(
new ParameterBag(),
$fixtures,
new ObjectBag(['dummy' => $secondNewObject])
);
$hydrator = new SimpleHydrator($hydrator, new FakeValueResolver());
$actual = $hydrator->hydrate($object, $set, $context);
$this->assertEquals($expected, $actual);
$hydratorProphecy->hydrate(Argument::cetera())->shouldHaveBeenCalledTimes(2);
}
public function testResolvesAllPropertyValues()
{
$object = new SimpleObject('dummy', new \stdClass());
$set = ResolvedFixtureSetFactory::create(
null,
$fixtures = (new FixtureBag())->with(
$fixture = new SimpleFixture(
'dummy',
\stdClass::class,
new SpecificationBag(
null,
(new PropertyBag())
->with($username = new Property('username', $usernameValue = new FakeValue()))
->with($group = new Property('group', $groupValue = new FakeValue()))
,
new MethodCallBag()
)
)
)
);
$context = new GenerationContext();
$context->markIsResolvingFixture('foo');
$resolverProphecy = $this->prophesize(ValueResolverInterface::class);
$setAfterFirstResolution = ResolvedFixtureSetFactory::create(new ParameterBag(['iteration' => 1]), $fixtures);
$resolverProphecy
->resolve(
$usernameValue,
$fixture,
$set,
[
'_instances' => $set->getObjects()->toArray(),
],
$context
)
->willReturn(
new ResolvedValueWithFixtureSet('Bob', $setAfterFirstResolution)
)
;
$setAfterSecondResolution = ResolvedFixtureSetFactory::create(new ParameterBag(['iteration' => 2]), $fixtures);
$resolverProphecy
->resolve(
$groupValue,
$fixture,
$setAfterFirstResolution,
[
'_instances' => $set->getObjects()->toArray(),
'username' => 'Bob',
],
$context
)
->willReturn(
new ResolvedValueWithFixtureSet('Badass', $setAfterSecondResolution)
)
;
/** @var ValueResolverInterface $resolver */
$resolver = $resolverProphecy->reveal();
$hydratorProphecy = $this->prophesize(PropertyHydratorInterface::class);
$newInstance = new \stdClass();
$newInstance->username = 'Bob';
$newObject = $object->withInstance($newInstance);
$hydratorProphecy->hydrate($object, $username->withValue('Bob'), $context)->willReturn($newObject);
$secondNewInstance = clone $newInstance;
$secondNewInstance->group = 'Badass';
$secondNewObject = $object->withInstance($secondNewInstance);
$hydratorProphecy->hydrate($newObject, $group->withValue('Badass'), $context)->willReturn($secondNewObject);
/** @var PropertyHydratorInterface $hydrator */
$hydrator = $hydratorProphecy->reveal();
$expected = new ResolvedFixtureSet(
new ParameterBag(['iteration' => 2]),
$fixtures,
new ObjectBag(['dummy' => $secondNewObject])
);
$hydrator = new SimpleHydrator($hydrator, $resolver);
$actual = $hydrator->hydrate($object, $set, $context);
$this->assertEquals($expected, $actual);
}
public function testThrowsAGenerationThrowableIfResolutionFails()
{
$object = new SimpleObject('dummy', new \stdClass());
$set = ResolvedFixtureSetFactory::create(
null,
$fixtures = (new FixtureBag())->with(
$fixture = new SimpleFixture(
'dummy',
\stdClass::class,
new SpecificationBag(
null,
(new PropertyBag())
->with(new Property('username', $usernameValue = new FakeValue()))
->with(new Property('group', $groupValue = new FakeValue()))
,
new MethodCallBag()
)
)
)
);
$resolverProphecy = $this->prophesize(ValueResolverInterface::class);
$resolverProphecy
->resolve(Argument::cetera())
->willThrow(RootResolutionException::class)
;
/** @var ValueResolverInterface $resolver */
$resolver = $resolverProphecy->reveal();
$hydrator = new SimpleHydrator(new FakePropertyHydrator(), $resolver);
try {
$hydrator->hydrate($object, $set, new GenerationContext());
$this->fail('Expected exception to be thrown.');
} catch (GenerationThrowable $throwable) {
// Expected result
}
}
}
| mit |
slightly-askew/portfolio-2017 | src/elements/bubble/config.js | 1410 | //@flow
/*------------------------------------*\
DEFAULT CONFIG
Anything you change here will affect
all bubbles globally.
If you plan to use different bubble
types accross your aplication, it
may be prudent to pass a 'bubbleConfig'
prop object; declaring settings
above on a per-component basis, which
are then merged with defaults on
component render. Any of the below may be
accepted as a prop:
\*------------------------------------*/
const defaultConfig = {
viewBox: "0 0 178 78",
d:
"M25,23 C11.745166,23 1,33.745166 1,47 L1,52.9978729 C1,66.2527069 11.745166,76.9978729 25,76.9978729 L153,76.9978729 C166.254834,76.9978729 177,66.2527069 177,52.9978729 L177,47 C177,33.9832734 166.92557,23.3765036 154,23 C147.388075,22.9896454 145.377907,17.5116287 142,4 C141.5,2 140,1 138,1 C136,1 134.5,2 134,4 C130.601677,17.5932914 127.850706,23 122,23 L25,23 Z",
characterWidth: 10, //future - check Dom node for length of text
minTextWidth: 108,
textHeight: 36, // future - check DOM node for height of text.
textMargin: 18,
textColumns: 1,
//size: `1em`, // defaults 1; gets interpolated into the root styled-component (although beware current sizing.)
speachDirection: "top-right",
maskOrigin: {
x: 144,
y: 0
},
thresholds: {
x: 36,
y: 48
},
dividerWidth: 2,
textboxOrigin: {
x: 36,
y: 45
}
};
export default defaultConfig;
| mit |
Copyleaks/Java-Plagiarism-Checker | src/copyleaks/sdk/api/UserAuthentication.java | 6016 | /********************************************************************************
The MIT License(MIT)
Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
********************************************************************************/
package copyleaks.sdk.api;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import copyleaks.sdk.api.helpers.HttpURLConnection.CopyleaksClient;
import copyleaks.sdk.api.helpers.HttpURLConnection.HttpURLConnectionHelper;
import copyleaks.sdk.api.RequestMethod;
import copyleaks.sdk.api.exceptions.CommandFailedException;
import copyleaks.sdk.api.exceptions.SecurityTokenException;
import copyleaks.sdk.api.models.*;
import copyleaks.sdk.api.models.responses.*;
public class UserAuthentication
{
/**
* Login to Copyleaks authentication server.
*
* @param email
* Account email
* @param apiKey
* Copyleaks API key
* @return Login Token to use while accessing the API services
* @throws CommandFailedException
* This exception is thrown if an exception situation occurred
* during the processing of a command
* @throws IOException
* This exception is thrown if an exception situation occurred
* during the processing of an I/O operation.
*/
public static LoginToken Login(String email, String apiKey) throws IOException, CommandFailedException
{
LoginToken loginToken;
String json;
Gson gson = new GsonBuilder().setDateFormat(Settings.DateFormat).create();
// Open connection to Copyleaks and set properties
URL url = new URL(String.format("%1$s/%2$s/account/login-api", Settings.ServiceEntryPoint, Settings.ServiceVersion));
HttpURLConnection conn = null;
try
{
conn = CopyleaksClient.getClient(url, null, RequestMethod.POST, HttpContentTypes.Json,
HttpContentTypes.Json);
// Add parameters
Map<String, String> dic = new HashMap<String, String>();
dic.put("email", email);
dic.put("apiKey", apiKey);
String body = gson.toJson(dic);
CopyleaksClient.HandleString.attach(conn, body);
if (conn.getResponseCode() != 200)
throw new CommandFailedException(conn);
try (InputStream inputStream = new BufferedInputStream(conn.getInputStream());)
{
json = HttpURLConnectionHelper.convertStreamToString(inputStream);
}
}
finally
{
if (conn != null)
conn.disconnect();
}
loginToken = gson.fromJson(json, LoginToken.class);
if (json == null || json.isEmpty())
throw new RuntimeException("This request could not be processed.");
if (loginToken == null)
throw new RuntimeException("Unable to process server response.");
return loginToken;
}
/**
* Get your current credit balance
*
* @return Login Token to use while accessing the API services
* @param token
* @throws CommandFailedException
* This exception is thrown if an exception situation occured
* during the processing of a command
* @throws SecurityTokenException
* The login-token is undefined or expired
*/
public static int getCreditBalance(LoginToken token, eProduct product) throws SecurityTokenException, CommandFailedException
{
LoginToken.ValidateToken(token);
Gson gson = new GsonBuilder().create();
String json;
URL url;
HttpURLConnection conn = null;
try
{
url = new URL(String.format("%1$s/%2$s/%3$s/count-credits",
Settings.ServiceEntryPoint,
Settings.ServiceVersion,
productToWalletName(product)));
conn = CopyleaksClient.getClient(url, token, RequestMethod.GET, HttpContentTypes.Json,
HttpContentTypes.Json);
if (conn.getResponseCode() != 200)
throw new CommandFailedException(conn);
try (InputStream inputStream = new BufferedInputStream(conn.getInputStream()))
{
json = HttpURLConnectionHelper.convertStreamToString(inputStream);
}
}
catch (IOException e)
{
throw new RuntimeException(e.getMessage());
}
finally
{
if (conn != null)
conn.disconnect();
}
if (json == null || json.isEmpty())
throw new RuntimeException("Unable to process server response.");
CountCreditsResponse res = gson.fromJson(json, CountCreditsResponse.class);
return res.getAmount();
}
private static String productToWalletName(eProduct product)
{
switch(product)
{
case Academic:
return Settings.AcademicServicePage;
case Businesses:
return Settings.BusinessesServicePage;
case Websites:
return Settings.WebsitesServicePage;
default:
throw new RuntimeException("Unknown product type.");
}
}
}
| mit |
lamk/LK-Flat-UI-Kit | js/jquery.hoverdir.js | 5314 | /**
* jquery.hoverdir.js v1.1.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
'use strict';
$.HoverDir = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.HoverDir.defaults = {
speed : 300,
easing : 'ease',
hoverDelay : 0,
inverse : false
};
$.HoverDir.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.HoverDir.defaults, options );
// transition properties
this.transitionProp = 'all ' + this.options.speed + 'ms ' + this.options.easing;
// support for CSS transitions
//this.support = Modernizr.csstransitions;
// load the events
this._loadEvents();
},
_loadEvents : function() {
var self = this;
this.$el.on( 'mouseenter.hoverdir, mouseleave.hoverdir', function( event ) {
var $el = $( this ),
$hoverElem = $el.find( '.overlay' ),
direction = self._getDir( $el, { x : event.pageX, y : event.pageY } ),
styleCSS = self._getStyle( direction );
if( event.type === 'mouseenter' ) {
$hoverElem.hide().css( styleCSS.from );
clearTimeout( self.tmhover );
self.tmhover = setTimeout( function() {
$hoverElem.show( 0, function() {
var $el = $( this );
if( self.support ) {
$el.css( 'transition', self.transitionProp );
}
self._applyAnimation( $el, styleCSS.to, self.options.speed );
} );
}, self.options.hoverDelay );
}
else {
if( self.support ) {
$hoverElem.css( 'transition', self.transitionProp );
}
clearTimeout( self.tmhover );
self._applyAnimation( $hoverElem, styleCSS.from, self.options.speed );
}
} );
},
// credits : http://stackoverflow.com/a/3647634
_getDir : function( $el, coordinates ) {
// the width and height of the current div
var w = $el.width(),
h = $el.height(),
// calculate the x and y to get an angle to the center of the div from that x and y.
// gets the x value relative to the center of the DIV and "normalize" it
x = ( coordinates.x - $el.offset().left - ( w/2 )) * ( w > h ? ( h/w ) : 1 ),
y = ( coordinates.y - $el.offset().top - ( h/2 )) * ( h > w ? ( w/h ) : 1 ),
// the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123);
// first calculate the angle of the point,
// add 180 deg to get rid of the negative values
// divide by 90 to get the quadrant
// add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
direction = Math.round( ( ( ( Math.atan2(y, x) * (180 / Math.PI) ) + 180 ) / 90 ) + 3 ) % 4;
return direction;
},
_getStyle : function( direction ) {
var fromStyle, toStyle,
slideFromTop = { left : '0px', top : '-100%' },
slideFromBottom = { left : '0px', top : '100%' },
slideFromLeft = { left : '-100%', top : '0px' },
slideFromRight = { left : '100%', top : '0px' },
slideTop = { top : '0px' },
slideLeft = { left : '0px' };
switch( direction ) {
case 0:
// from top
fromStyle = !this.options.inverse ? slideFromTop : slideFromBottom;
toStyle = slideTop;
break;
case 1:
// from right
fromStyle = !this.options.inverse ? slideFromRight : slideFromLeft;
toStyle = slideLeft;
break;
case 2:
// from bottom
fromStyle = !this.options.inverse ? slideFromBottom : slideFromTop;
toStyle = slideTop;
break;
case 3:
// from left
fromStyle = !this.options.inverse ? slideFromLeft : slideFromRight;
toStyle = slideLeft;
break;
};
return { from : fromStyle, to : toStyle };
},
// apply a transition or fallback to jquery animate based on Modernizr.csstransitions support
_applyAnimation : function( el, styleCSS, speed ) {
$.fn.applyStyle = this.support ? $.fn.css : $.fn.animate;
el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms' } ) );
},
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.hoverdir = function( options ) {
var instance = $.data( this, 'hoverdir' );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on hoverdir prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for hoverdir instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'hoverdir', new $.HoverDir( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
| mit |
SullyJHF/learn-to-code | done/pong/src/pong/Paddle.java | 1326 | package pong;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import com.sun.glass.events.KeyEvent;
public class Paddle {
private float x, y;
private float w;
private float h;
private Color color;
private float speed;
private boolean left;
public Paddle(boolean left) {
this.left = left;
this.h = 125;
this.w = 13;
this.x = this.left ? this.w : Screen.WIDTH - 2 * this.w;
this.y = Screen.HEIGHT / 2 - this.h / 2;
this.speed = 1.5f;
this.color = Color.WHITE;
}
public void draw(Graphics2D g2d) {
g2d.setColor(this.color);
g2d.fillRect(
(int) this.x,
(int) this.y,
(int) this.w,
(int) this.h);
}
public void tick(boolean[] keys) {
if (this.left) {
// player 1
if (keys[KeyEvent.VK_W]) moveUp();
if (keys[KeyEvent.VK_S]) moveDown();
} else {
// player 2
if (keys[KeyEvent.VK_UP]) moveUp();
if (keys[KeyEvent.VK_DOWN]) moveDown();
}
}
private void moveUp() {
if (y > 0)
this.y -= this.speed;
}
private void moveDown() {
if (y + h < Screen.HEIGHT)
this.y += this.speed;
}
public Shape getBounds() {
Shape bounds = new Rectangle.Double(this.x, this.y, this.w, this.h);
return bounds;
}
}
| mit |