text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="bpmis.pxc.system.pojo.Role" table="t_role" lazy="false">
		<id name="id" column="id" type="java.lang.Integer">
		  <generator class="identity" />
		</id>
		<property name="rolename" length="50"  column="rolename" type="java.lang.String"></property>
		<property name="remark" length="500"  column="remark" type="java.lang.String"></property>

        </class>
</hibernate-mapping>


text:
// Posix aggregator inlines.

#ifndef O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__
#define O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__

#include <string>
#include "aggregator-posix.h"

namespace stats_report {

template <typename ValueType>
bool MetricsAggregatorPosix::GetValue(const string &key, ValueType *value) {
  StartAggregation();
  bool success = transaction_->Get(key, value);
  EndAggregation();
  return success;
}

template <typename ValueType>
bool MetricsAggregatorPosix::SetValue(const string &key, ValueType value) {
  StartAggregation();
  bool success = transaction_->Put(key, value);
  EndAggregation();
  return success;
}

}  // namespace stats_report

#endif  // O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__

redpajama_set_name: RedPajamaGithub


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
using System.Xml.Serialization;

namespace Summer.Batch.Core.Unity.Xml
{
    /// <summary>
    /// Xml representation of partition.
    /// </summary>
    public class XmlPartition
    {
        /// <summary>
        /// mapper
        /// </summary>
        [XmlElement("mapper")]
        public XmlPartitionMapper Mapper { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;

namespace IIS.SLSharp
{
    public static class Extensions
    {
        public static TSource Max<TSource, TSelect>(this IEnumerable<TSource> source, Func<TSource, TSelect> selector)
            where TSelect : IComparable<TSelect>
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (selector == null)
                throw new ArgumentNullException("selector");

            var enumer = source.GetEnumerator();

            enumer.MoveNext();
            var maxItem = enumer.Current;
            var maxValue = selector(maxItem);

            while (enumer.MoveNext())
            {
                var currentItem = enumer.Current;
                var currentValue = selector(currentItem);

                if (currentValue.CompareTo(maxValue) <= 0)
                    continue;

                maxItem = currentItem;
                maxValue = currentValue;
            }

            return maxItem;
        }

        public static TSource Min<TSource, TSelect>(this IEnumerable<TSource> source, Func<TSource, TSelect> selector)
            where TSelect : IComparable<TSelect>
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (selector == null)
                throw new ArgumentNullException("selector");

            var enumer = source.GetEnumerator();

            enumer.MoveNext();
            var minItem = enumer.Current;
            var minValue = selector(minItem);

            while (enumer.MoveNext())
            {
                var currentItem = enumer.Current;
                var currentValue = selector(currentItem);

                if (currentValue.CompareTo(minValue) >= 0)
                    continue;

                minItem = currentItem;
                minValue = currentValue;
            }

            return minItem;
        }
    }
}


text:
@implementation ABSaveSystem

#pragma mark - Helper
+(NSString*) appName
{
    NSString *bundlePath = [[[NSBundle mainBundle] bundleURL] lastPathComponent];
    return [[bundlePath stringByDeletingPathExtension] lowercaseString];
}

+(ABSaveSystemOS) os
{
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
    return ABSaveSystemOSIOS;
#else
    return ABSaveSystemOSMacOSX;
#endif
}

+(NSString*) filepathEncrypted:(BOOL)encrypted
{
    ABSaveSystemOS os = [self os];

    NSString *fileExt = (encrypted) ? @".abssen" : @".abss";
    NSString *fileName = [NSString stringWithFormat:@"%@%@", [[self appName] lowercaseString], fileExt];

    if (os == ABSaveSystemOSIOS)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths safeObjectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
        return path;
    }
    else if (os == ABSaveSystemOSMacOSX)
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *folderPath = [NSString stringWithFormat:@"~/Library/Application Support/%@/", [self appName]];
        folderPath = [folderPath stringByExpandingTildeInPath];
        if ([fileManager fileExistsAtPath:folderPath] == NO)
        {
            [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
        }
        return  [folderPath stringByAppendingPathComponent:fileName];
    }

    return nil;
}

+(NSMutableDictionary*) loadEncryptedDictionary:(BOOL)encrypted
{
    NSData *binaryFile = [NSData dataWithContentsOfFile:[self filepathEncrypted:encrypted]];

    if (binaryFile == nil) {
        return nil;
    }

    NSMutableDictionary *dictionary;
    //Either Decrypt saved data or just load it
    if (encrypted)
    {
        NSData *dataKey = [ABSAVESYSTEM_AESKEY dataUsingEncoding:NSUTF8StringEncoding];
        NSData *decryptedData = [binaryFile decryptedWithKey:dataKey];
        dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:decryptedData];
    }
    else
    {
        dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:binaryFile];
    }

    return dictionary;
}

#pragma mark - Objects
#pragma mark - NSData
+(void) saveData:(NSData*)data key:(NSString*)key encrypted:(BOOL)encrypted
{
    //Check if file exits, if so init Dictionary with it's content, otherwise allocate new one
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[self filepathEncrypted:encrypted]];
    NSMutableDictionary *tempDic = nil;
    if (fileExists == NO) {
        tempDic = [[NSMutableDictionary alloc] init];
    } else {
        tempDic = [self loadEncryptedDictionary:encrypted];
    }

    //Populate Dictionary with to save value/key and write to file
    [tempDic setObject:data forKey:key];

    NSData *dicData = [NSKeyedArchiver archivedDataWithRootObject:tempDic];

    //Either encrypt Data or just save
    if (encrypted)
    {
        NSData *dataKey = [ABSAVESYSTEM_AESKEY dataUsingEncoding:NSUTF8StringEncoding];
        NSData *encryptedData = [dicData encryptedWithKey:dataKey];
        [encryptedData writeToFile:[self filepathEncrypted:YES] atomically:YES];
    }
    else
    {
        [dicData writeToFile:[self filepathEncrypted:encrypted] atomically:YES];
    }

}

+(void) saveData:(NSData*)data key:(NSString*)key
{
    [self saveData:data key:key encrypted:ABSAVESYSTEM_ENCRYPTION_ENABLED];
}

+(NSData*) dataForKey:(NSString*)key encrypted:(BOOL)encrypted
{
    NSMutableDictionary *tempDic = [self loadEncryptedDictionary:encrypted];

    //Retrieve NSData for specific key
    NSData *loadedData = [tempDic objectForKey:key];

    //Check if data exists for key
    if (loadedData != nil)
    {
        return loadedData;
    }
    else
    {
        if (ABSAVESYSTEM_VERBOSE_LOGGING) NSLog(@"ABSaveSystem ERROR: dataForKey:\"%@\" -> data for key does not exist!", key);
    }
    return nil;
}

+(NSData*) dataForKey:(NSString*)key
{
    return [self dataForKey:key encrypted:ABSAVESYSTEM_ENCRYPTION_ENABLED];
}

#pragma mark - Object
+(void) saveObject:(id<NSCoding>)object key:(NSString*)key
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self saveData:data key:key];
}

+(id) objectForKey:(NSString*)key checkClass:(Class)aClass
{
    NSData *data = [self dataForKey:key];
    if (data != nil)
    {
        //Check that the correct kind of class was retrieved from storage (skip check if aClass is not set)
        id object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if ([object isKindOfClass:aClass] || aClass == nil)
        {
            return object;
        }
        else
        {
            if (ABSAVESYSTEM_LOGGING) NSLog(@"ABSaveSystem ERROR: objectForKey:\"%@\" -> saved object is %@ not a %@", key, [object class],  aClass);
        }
    }
    return nil;
}

+(id) objectForKey:(NSString*)key
{
    return [self objectForKey:key checkClass:nil];
}

#pragma mark - NSString
+(void) saveString:(NSString*)string key:(NSString*)key
{
    [self saveObject:string key:key];
}

+(NSString*) stringForKey:(NSString*)key
{
    return [self objectForKey:key checkClass:[NSString class]];
}

#pragma mark - NSNumber
+(void) saveNumber:(NSNumber*)number key:(NSString*)key
{
    [self saveObject:number key:key];
}

+(NSNumber*) numberForKey:(NSString*)key
{
    return [self objectForKey:key checkClass:[NSNumber class]];
}

#pragma mark - NSDate
+(void) saveDate:(NSDate*)date key:(NSString*)key
{
    [self saveObject:date key:key];
}

+(NSDate*) dateForKey:(NSString*)key
{
    return [self objectForKey:key checkClass:[NSDate class]];
}

#pragma mark - Primitives
#pragma mark - NSInteger
+(void) saveInteger:(NSInteger)integer key:(NSString*)key
{
    [self saveNumber:[NSNumber numberWithInteger:integer] key:key];
}

+(NSInteger) integerForKey:(NSString*)key
{
    NSNumber *number = [self numberForKey:key];
    if (number != nil) {
        return [number integerValue];
    }
    return 0;
}

#pragma mark - CGFloat
+(void) saveFloat:(CGFloat)aFloat key:(NSString*)key
{
    [self saveNumber:[NSNumber numberWithFloat:aFloat] key:key];
}

+(CGFloat) floatForKey:(NSString*)key
{
    NSNumber *number = [self numberForKey:key];
    if (number != nil) {
        return [number floatValue];
    }
    return 0.0f;
}

#pragma mark - BOOL
+(void) saveBool:(BOOL)boolean key:(NSString*)key
{
    [self saveNumber:[NSNumber numberWithBool:boolean] key:key];
}

+(BOOL) boolForKey:(NSString*)key
{
    NSNumber *number = [self numberForKey:key];
    if (number != nil) {
        return [number boolValue];
    }
    return NO;
}

#pragma mark - Misc
+(BOOL) exists:(NSString*)key
{
    return [self exists:key encrypted:ABSAVESYSTEM_ENCRYPTION_ENABLED];
}

+(BOOL) exists:(NSString*)key encrypted:(BOOL)encrypted
{
    id data = [self dataForKey:key encrypted:encrypted];
    return (data != nil);
}

+(void) logSavedValues:(BOOL)encrypted
{
    NSString *baseLogMessage = (encrypted) ? @"ABSaveSystem: logSavedValues (Encrypted)" : @"ABSaveSystem: logSavedValues";

    NSMutableDictionary *tempDic= [self loadEncryptedDictionary:encrypted];
    if (tempDic == nil)
    {
        NSLog(@"%@ -> NO DATA SAVED!", baseLogMessage);
        return;
    }

    NSLog(@"%@ -> START LOG", baseLogMessage);

    [tempDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
     {
         NSString *valueString = [NSKeyedUnarchiver unarchiveObjectWithData:obj];

         NSLog(@"%@ -> Key:%@ -> %@", baseLogMessage, key, valueString);
     }];

    NSLog(@"%@ -> END LOG", baseLogMessage);
}

+(void) truncate
{
    [self truncateEncrypted:NO];
    [self truncateEncrypted:YES];
}

+(void) truncateEncrypted:(BOOL)encrypted
{
    NSString *filepath = [self filepathEncrypted:encrypted];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:filepath])
    {
        [fileManager removeItemAtPath:filepath error:nil];
    }
}

+(void) removeValueForKey:(NSString*)key
{
    [self removeValueForKey:key encrypted:ABSAVESYSTEM_ENCRYPTION_ENABLED];
}

+(void) removeValueForKey:(NSString*)key encrypted:(BOOL)encrypted
{
    NSMutableDictionary *tempDic = [self loadEncryptedDictionary:encrypted];
    [tempDic removeObjectForKey:key];

    NSData *dicData = [NSKeyedArchiver archivedDataWithRootObject:tempDic];

    if (encrypted)
    {
        NSData *dataKey = [ABSAVESYSTEM_AESKEY dataUsingEncoding:NSUTF8StringEncoding];
        NSData *encryptedData = [dicData encryptedWithKey:dataKey];
        [encryptedData writeToFile:[self filepathEncrypted:YES] atomically:YES];
    }
    else
    {
        NSData *dicData = [NSKeyedArchiver archivedDataWithRootObject:tempDic];
        [dicData writeToFile:[self filepathEncrypted:NO] atomically:YES];
    }
}

@end


text:
using System;
using Telegram.Bot.Types;

namespace Telegram.Bot.Args
{
    /// <summary>
    /// <see cref="EventArgs"/> containing a <see cref="Types.ChosenInlineResult"/>
    /// </summary>
    /// <seealso cref="EventArgs" />
    public class ChosenInlineResultEventArgs : EventArgs
    {
        /// <summary>
        /// Gets the chosen inline result.
        /// </summary>
        /// <value>
        /// The chosen inline result.
        /// </value>
        public ChosenInlineResult ChosenInlineResult { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChosenInlineResultEventArgs"/> class.
        /// </summary>
        /// <param name="update">The update.</param>
        internal ChosenInlineResultEventArgs(Update update)
        {
            ChosenInlineResult = update.ChosenInlineResult;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChosenInlineResultEventArgs"/> class.
        /// </summary>
        /// <param name="chosenInlineResult">The chosen inline result.</param>
        internal ChosenInlineResultEventArgs(ChosenInlineResult chosenInlineResult)
        {
            ChosenInlineResult = chosenInlineResult;
        }

        /// <summary>
        /// Performs an implicit conversion from <see cref="UpdateEventArgs"/> to <see cref="ChosenInlineResultEventArgs"/>.
        /// </summary>
        /// <param name="e">The <see cref="UpdateEventArgs"/> instance containing the event data.</param>
        /// <returns>
        /// The result of the conversion.
        /// </returns>
        public static implicit operator ChosenInlineResultEventArgs(UpdateEventArgs e) => new ChosenInlineResultEventArgs(e.Update);
    }
}


text:
traprestart()
{
$0 "$$" &
exit 0
}
trap traprestart HUP TERM INT
# Run like this:
# nohup./util-daemon.sh /your/filesystem/ 10 &
# The "10" is the loop rate in seconds. Ten is okay on most systems.
UDIR="$1"

mkdir -p $UDIR/log
touch $UDIR/util.sleep
echo $3 > $UDIR/util.sleep

# Do reporting with these congfiguration files.
# They need to be in place.
# Edit the config files with comma delimited search regrexes.
# Example for blacklist.conf:
# facebook.com, otherplace, 192.168.1.22
# This will not stop facebook.com, just let you know that the server is connected to it.
# The mother-daemon.sh can react to the output for further processing, including
# killing the connection.

# Each config only takes up to three entries. If you need more, expand the greps!
# Edit line 74 to set the desired email address.

# Alert for specific network connections
touch $UDIR/blacklist.conf
# Check on a network processes
touch $UDIR/netp.conf
# Look for a process to be stopped
touch $UDIR/killproc.conf
# Check for a running proess
touch $UDIR/procp.conf

gather() {
    df -h > $UDIR/df.out
    uptime > $UDIR/uptime.out
    netstat -a | grep -v unix > $UDIR/netstat.out
    ps aux > $UDIR/ps.out
}

report() {

ly=$(which lynis)

if [ -z "$ly" ]; then
    lynis && cp /var/log/lynis-report.dat $UIDR/log/
else
    echo "No lynis installed!" > $UDIR/log/lynis.warn
fi

    grep [9][7-9]% $UDIR/df.out > $UDIR/log/df.warn
    grep "100%" $UDIR/df.out > $UDIR/log/df.alert
    grep keeper-daemon.sh $UDIR/ps.out > $UDIR/log/keeper.warn
    grep install-daemon.sh $UDIR/ps.out > $UDIR/log/install.warn
    grep mother-daemon.sh $UDIR/ps.out > $UDIR/log/mother.warn
    grep util-daemon.sh $UDIR/ps.out > $UDIR/log/util.warn
    grep cop-daemon.sh $UDIR/ps.out > $UDIR/log/cop.warn
    PROCLIM=$(cat /proc/cpuinfo | grep processor | wc -l)
    grep [["$PROCLIM"-9]][0-9].[0-9][0-9] $UDIR/uptime.out > $UDIR/log/load.warn
    grep [1-9][0-9][0-9].[0-9][0-9] $UDIR/uptime.out > $UDIR/log/load.alert
    grep [1-9][0-9][0-9][0-9].[0-9][0-9] $UDIR/uptime.out > $UDIR/log/load2.alert
    grep [1-9][0-9][0-9][0-9][0-9].[0-9][0-9] $UDIR/uptime.out > $UDIR/log/load3.alert
    grep $(cat $UDIR/blacklist.conf | cut -d',' -f1) $UDIR/netstat.out > $UDIR/log/blacklist.warn
    grep $(cat $UDIR/netp.conf | cut -d',' -f1) $UDIR/netstat.out > $UDIR/log/netp.log
    grep $(cat $UDIR/killproc.conf | cut -d',' -f1) $UDIR/ps.out > $UDIR/log/killproc.warn
    grep $(cat $UDIR/procp.conf | cut -d',' -f1) $UDIR/ps.out > $UDIR/log/procp.log
    grep $(cat $UDIR/blacklist.conf | cut -d',' -f2) $UDIR/netstat.out > $UDIR/log/blacklist2.warn
    grep $(cat $UDIR/netp.conf | cut -d',' -f2) $UDIR/netstat.out > $UDIR/log/netp2.log
    grep $(cat $UDIR/killproc.conf | cut -d',' -f1) $UDIR/ps.out > $UDIR/log/killproc.warn
    grep $(cat $UDIR/procp.conf | cut -d',' -f1) $UDIR/ps.out > $UDIR/log/procp.log
    grep $(cat $UDIR/blacklist.conf | cut -d',' -f2) $UDIR/netstat.out > $UDIR/log/blacklist2.warn
    grep $(cat $UDIR/netp.conf | cut -d',' -f2) $UDIR/netstat.out > $UDIR/log/netp2.log
    grep $(cat $UDIR/killproc.conf | cut -d',' -f2) $UDIR/ps.out > $UDIR/log/killproc2.warn
    grep $(cat $UDIR/procp.conf | cut -d',' -f2) $UDIR/ps.out > $UDIR/log/procp2.log
    grep $(cat $UDIR/blacklist.conf | cut -d',' -f3) $UDIR/netstat.out > $UDIR/log/blacklist3.warn
    grep $(cat $UDIR/netp.conf | cut -d',' -f3) $UDIR/netstat.out > $UDIR/log/netp3.log
    grep $(cat $UDIR/killproc.conf | cut -d',' -f3) $UDIR/ps.out > $UDIR/log/killproc3.warn
    grep $(cat $UDIR/procp.conf | cut -d',' -f3) $UDIR/ps.out > $UDIR/log/procp3.log
}

email() {
    echo "Utility Daemon Report $(date) from $(uname -a)" > $UDIR/logreport
    cat $UDIR/log/* >> $UDIR/logreport
#
#          SET THE EMAIL BY EDITING THE SCRIPT HERE--------------------------------------------------
#                                                                                |
#                                                                                \ /
#                                                                                V
    echo "$(cat $UDIR/logreport)" | mailx -s "Utility Daemon Report $(date)" example@someplace.com
}

touch $UDIR/email.send

# If there is anything in email.send, emails will be sent continously!
# It can be a lot of emails. Use with caution.
# Example way to use the email.send file:
# echo 1 > $UDIR/email.send && sleep 300 && cp /dev/null $UDIR/email.send
# That sends emails for five minutes then stops them. Something like that could be used in a cron entry etc.

checkemail() {
if [ -s $UDIR/email.send ]
then
     echo "EMAILING REPORT"
     email
else
    gather
    report
fi
}

while true; do
    gather
    report & # If one of the greps hangs, the daemon just moves on...
    checkemail
    sleep $(cat $UDIR/util.sleep)
done

# Set the sleep amount in seconds by placing a number in $UDIR/util.sleep:wq


text:
from datetime import timedelta, datetime

from aleph.core import db, archive
from aleph.model import Export
from aleph.logic.export import create_export, delete_expired_exports, complete_export
from aleph.logic.notifications import get_notifications
from aleph.tests.util import TestCase

class ExportsTestCase(TestCase):
    def setUp(self):
        super(ExportsTestCase, self).setUp()
        self.load_fixtures()
        self.email = "test@pudo.org"
        self.role_email = self.create_user("with_email", email=self.email)

        csv_path = self.get_fixture_path("experts.csv")
        temp_path = self._create_temporary_copy(csv_path, "experts.csv")
        self.export1 = create_export("TEST", self.role_email.id, "test1")
        complete_export(self.export1.id, temp_path, "experts.csv")

        temp_path = self._create_temporary_copy(csv_path, "experts.csv")
        self.export2 = create_export("TEST", self.role_email.id, "test2")
        self.export2.expires_at = datetime.utcnow() + timedelta(days=-1)
        complete_export(self.export2.id, temp_path, "experts.csv")

        source_path = self.get_fixture_path("../util.py")
        temp_path = self._create_temporary_copy(source_path, "init.py")
        self.export3 = create_export("TEST", self.role_email.id, "test3")
        self.export3.expires_at = datetime.utcnow() + timedelta(days=-1)
        complete_export(self.export3.id, temp_path, "init.py")

    def test_create(self):
        assert self.export1.content_hash is not None
        assert self.export1.content_hash == self.export2.content_hash
        assert archive.load_file(self.export1.content_hash) is not None
        assert archive.load_file(self.export1.content_hash) == archive.load_file(
            self.export2.content_hash
        )
        assert self.export1.file_name == self.export2.file_name == "experts.csv"

        res = get_notifications(self.role_email)
        notification_count = res.get("hits").get("total").get("value")
        assert notification_count == 3, notification_count

    def test_delete_expired(self):
        q = Export.by_role_id(self.role_email.id, deleted=True)
        assert q.count() == 3, q.count()

        delete_expired_exports()
        q = Export.by_role_id(self.role_email.id)
        assert q.count() == 1, q.count()
        exp1 = Export.by_id(self.export1.id, deleted=False)
        assert exp1 is not None
        assert exp1.deleted is False
        exp2 = Export.by_id(self.export2.id, deleted=True)
        assert exp2 is not None
        assert exp2.deleted is True

        path = archive.load_file(self.export1.content_hash)
        assert path is not None
        assert path.exists()

        exp1.expires_at = datetime.utcnow() + timedelta(days=-1)
        db.session.add(exp1)
        db.session.commit()

        delete_expired_exports()
        q = Export.by_role_id(self.role_email.id)
        assert q.count() == 0, q.count()
        exp1 = Export.by_id(self.export1.id, deleted=True)
        assert exp1 is not None
        assert exp1.deleted is True
        path = archive.load_file(self.export1.content_hash)
        assert path is not None, path

        path = archive.load_file(self.export3.content_hash)
        assert path is None, path


text:
package org.apache.hadoop.filecache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Random;

import javax.security.auth.login.LoginException;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.TaskDistributedCacheManager.CacheFile;
import org.apache.hadoop.mapred.DefaultTaskController;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.JobLocalizer;
import org.apache.hadoop.mapred.TaskController;
import org.apache.hadoop.mapred.TaskTracker;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.filecache.TaskDistributedCacheManager;
import org.apache.hadoop.filecache.TrackerDistributedCacheManager;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.ReflectionUtils;

public class TestTrackerDistributedCacheManager extends TestCase {
  private static final Log LOG =
    LogFactory.getLog(TestTrackerDistributedCacheManager.class);

  protected String TEST_ROOT_DIR =
      new File(System.getProperty("test.build.data", "/tmp"),
          TestTrackerDistributedCacheManager.class.getSimpleName())
          .getAbsolutePath();

  protected File ROOT_MAPRED_LOCAL_DIR;
  protected int numLocalDirs = 6;

  private static final int TEST_FILE_SIZE = 4 * 1024; // 4K
  private static final int LOCAL_CACHE_LIMIT = 5 * 1024; //5K
  private static final int LOCAL_CACHE_SUBDIR_LIMIT = 1;
  protected Configuration conf;
  protected Path firstCacheFile;
  protected Path firstCacheFilePublic;
  protected Path secondCacheFile;
  protected Path secondCacheFilePublic;
  private FileSystem fs;

  protected LocalDirAllocator localDirAllocator =
    new LocalDirAllocator("mapred.local.dir");
  protected TaskController taskController;

  @Override
  protected void setUp() throws IOException,InterruptedException {

    // Prepare the tests' root dir
    File TEST_ROOT = new File(TEST_ROOT_DIR);
    if (!TEST_ROOT.exists()) {
      TEST_ROOT.mkdirs();
    }

    conf = new Configuration();
    conf.set(FileSystem.FS_DEFAULT_NAME_KEY, "file:///");
    fs = FileSystem.get(conf);

    // This test suite will fail if any ancestor directory of the
    // test directory is not world-searchable (ie +x).
    // We prefer to fail the test in an obvious manner up front
    // during setUp() rather than in a subtle way later.
    assertTrue("Test root directory " + TEST_ROOT + " and all of its " +
               "parent directories must have a+x permissions",
               TrackerDistributedCacheManager.ancestorsHaveExecutePermissions(
                 fs, new Path(TEST_ROOT.toString())));

    // Prepare the tests' mapred-local-dir
    ROOT_MAPRED_LOCAL_DIR = new File(TEST_ROOT_DIR, "mapred/local");
    ROOT_MAPRED_LOCAL_DIR.mkdirs();

    String []localDirs = new String[numLocalDirs];
    for (int i = 0; i < numLocalDirs; i++) {
      File localDir = new File(ROOT_MAPRED_LOCAL_DIR, "0_" + i);
      localDirs[i] = localDir.getPath();
      localDir.mkdir();
    }

    conf.setStrings("mapred.local.dir", localDirs);
    Class<? extends TaskController> taskControllerClass = conf.getClass(
        "mapred.task.tracker.task-controller", DefaultTaskController.class,
        TaskController.class);
    taskController = (TaskController) ReflectionUtils.newInstance(
        taskControllerClass, conf);

    // setup permissions for mapred local dir
    taskController.setup(localDirAllocator);

    // Create the temporary cache files to be used in the tests.
    firstCacheFile = new Path(TEST_ROOT_DIR, "firstcachefile");
    secondCacheFile = new Path(TEST_ROOT_DIR, "secondcachefile");
    firstCacheFilePublic = new Path(TEST_ROOT_DIR, "firstcachefileOne");
    secondCacheFilePublic = new Path(TEST_ROOT_DIR, "secondcachefileOne");
    createPublicTempFile(firstCacheFilePublic);
    createPublicTempFile(secondCacheFilePublic);
    createPrivateTempFile(firstCacheFile);
    createPrivateTempFile(secondCacheFile);
  }

  protected void refreshConf(Configuration conf) throws IOException {
    taskController.setConf(conf);
    taskController.setup(localDirAllocator);
  }

  /**
   * Whether the test can run on the machine
   *
   * @return true if test can run on the machine, false otherwise
   */
  protected boolean canRun() {
    return true;
  }

  /**
   * This is the typical flow for using the DistributedCache classes.
   *
   * @throws IOException
   * @throws LoginException
   */
  public void testManagerFlow() throws IOException, LoginException {
    if (!canRun()) {
      return;
    }

    // ****** Imitate JobClient code
    // Configures a task/job with both a regular file and a "classpath" file.
    Configuration subConf = new Configuration(conf);
    String userName = getJobOwnerName();
    subConf.set("user.name", userName);
    JobID jobid = new JobID("jt",1);
    DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf);
    DistributedCache.addFileToClassPath(secondCacheFile, subConf,
                                        FileSystem.get(subConf));
    TrackerDistributedCacheManager.determineTimestamps(subConf);
    TrackerDistributedCacheManager.determineCacheVisibilities(subConf);
    // ****** End of imitating JobClient code

    Path jobFile = new Path(TEST_ROOT_DIR, "job.xml");
    FileOutputStream os = new FileOutputStream(new File(jobFile.toString()));
    subConf.writeXml(os);
    os.close();

    // ****** Imitate TaskRunner code.
    TrackerDistributedCacheManager manager =
      new TrackerDistributedCacheManager(conf, taskController);
    TaskDistributedCacheManager handle =
      manager.newTaskDistributedCacheManager(jobid, subConf);
    assertNull(null, DistributedCache.getLocalCacheFiles(subConf));
    File workDir = new File(new Path(TEST_ROOT_DIR, "workdir").toString());
    handle.setupCache(subConf, TaskTracker.getPublicDistributedCacheDir(),
        TaskTracker.getPrivateDistributedCacheDir(userName));
    JobLocalizer.downloadPrivateCache(subConf);
    // DOESN'T ACTUALLY HAPPEN IN THE TaskRunner (THIS IS A TODO)
//    handle.setupPrivateCache(localDirAllocator, TaskTracker
//        .getPrivateDistributedCacheDir(userName));
//    // ****** End of imitating TaskRunner code

    Path[] localCacheFiles = DistributedCache.getLocalCacheFiles(subConf);
    assertNotNull(null, localCacheFiles);
    assertEquals(2, localCacheFiles.length);
    Path cachedFirstFile = localCacheFiles[0];
    Path cachedSecondFile = localCacheFiles[1];
    assertFileLengthEquals(firstCacheFile, cachedFirstFile);
    assertFalse("Paths should be different.",
        firstCacheFile.equals(cachedFirstFile));

    assertEquals(1, handle.getClassPaths().size());
    assertEquals(cachedSecondFile.toString(), handle.getClassPaths().get(0));

    checkFilePermissions(localCacheFiles);

    // Cleanup
    handle.release();
    manager.purgeCache();
    assertFalse(pathToFile(cachedFirstFile).exists());
  }

  /**
   * This DistributedCacheManager fails in localizing firstCacheFile.
   */
  public class FakeTrackerDistributedCacheManager extends
      TrackerDistributedCacheManager {
    public FakeTrackerDistributedCacheManager(Configuration conf)
        throws IOException {
      super(conf, taskController);
    }

    @Override
    Path localizePublicCacheObject(Configuration conf, URI cache,
                                   long confFileStamp,
                                   CacheStatus cacheStatus,
                                   FileStatus fileStatus,
                                   boolean isArchive) throws IOException {
      if (cache.equals(firstCacheFilePublic.toUri())) {
        throw new IOException("fake fail");
      }
      return super.localizePublicCacheObject(conf, cache, confFileStamp,
                                             cacheStatus, fileStatus,
                                             isArchive);
    }
  }

  public void testReferenceCount() throws IOException, LoginException,
      URISyntaxException, InterruptedException {
    if (!canRun()) {
      return;
    }
    TrackerDistributedCacheManager manager =
      new FakeTrackerDistributedCacheManager(conf);

    String userName = getJobOwnerName();
    File workDir = new File(new Path(TEST_ROOT_DIR, "workdir").toString());

    // Configures a job with a regular file
    Job job1 = new Job(conf);
    Configuration conf1 = job1.getConfiguration();
    conf1.set("user.name", userName);
    DistributedCache.addCacheFile(secondCacheFile.toUri(), conf1);

    TrackerDistributedCacheManager.determineTimestamps(conf1);
    TrackerDistributedCacheManager.determineCacheVisibilities(conf1);

    // Task localizing for first job
    TaskDistributedCacheManager handle = manager
        .newTaskDistributedCacheManager(new JobID("jt", 1), conf1);
    handle.setupCache(conf1, TaskTracker.getPublicDistributedCacheDir(),
        TaskTracker.getPrivateDistributedCacheDir(userName));
    JobLocalizer.downloadPrivateCache(conf1);
    handle.release();
    for (TaskDistributedCacheManager.CacheFile c : handle.getCacheFiles()) {
      assertEquals(0, manager.getReferenceCount(c.getStatus()));
    }

    Path thirdCacheFile = new Path(TEST_ROOT_DIR, "thirdcachefile");
    createPrivateTempFile(thirdCacheFile);

    // Configures another job with three regular files.
    Job job2 = new Job(conf);
    Configuration conf2 = job2.getConfiguration();
    conf2.set("user.name", userName);
    // add a file that would get failed to localize
    DistributedCache.addCacheFile(firstCacheFilePublic.toUri(), conf2);
    // add a file that is already localized by different job
    DistributedCache.addCacheFile(secondCacheFile.toUri(), conf2);
    // add a file that is never localized
    DistributedCache.addCacheFile(thirdCacheFile.toUri(), conf2);

    TrackerDistributedCacheManager.determineTimestamps(conf2);
    TrackerDistributedCacheManager.determineCacheVisibilities(conf2);

    // Task localizing for second job
    // localization for the "firstCacheFile" will fail.
    handle = manager.newTaskDistributedCacheManager(new JobID("jt", 2), conf2);
    Throwable th = null;
    try {
      handle.setupCache(conf2, TaskTracker.getPublicDistributedCacheDir(),
          TaskTracker.getPrivateDistributedCacheDir(userName));
      JobLocalizer.downloadPrivateCache(conf2);
    } catch (IOException e) {
      th = e;
      LOG.info("Exception during setup", e);
    }
    assertNotNull(th);
    assertTrue(th.getMessage().contains("fake fail"));
    handle.release();
    th = null;
    for (TaskDistributedCacheManager.CacheFile c : handle.getCacheFiles()) {
      try {
        int refcount = manager.getReferenceCount(c.getStatus());
        LOG.info("checking refcount " + c.uri + " of " + refcount);
        assertEquals(0, refcount);
      } catch (NullPointerException ie) {
        th = ie;
        LOG.info("Exception getting reference count for " + c.uri, ie);
      }
    }
    assertNotNull(th);
    fs.delete(thirdCacheFile, false);
  }

  /**
   * Tests that localization of distributed cache file happens in the desired
   * directory
   * @throws IOException
   * @throws LoginException
   */
  public void testPublicPrivateCache()
  throws IOException, LoginException, InterruptedException {
    if (!canRun()) {
      return;
    }
    checkLocalizedPath(true);
    checkLocalizedPath(false);
  }

  private void appendStringArray(StringBuilder buffer, String[] data) {
    if (data != null && data.length != 0) {
      buffer.append(data[0]);
      for(int i=1; i < data.length; i++) {
        buffer.append(',');
        buffer.append(data[i]);
      }
    }
  }

  private void appendBooleanArray(StringBuilder buffer, boolean[] data) {
    if (data != null && data.length != 0) {
      buffer.append(data[0]);
      for(int i=1; i < data.length; i++) {
        buffer.append(',');
        buffer.append(data[i]);
      }
    }
  }

  private void appendLongArray(StringBuilder buffer, long[] data) {
    if (data != null && data.length != 0) {
      buffer.append(data[0]);
      for(int i=1; i < data.length; i++) {
        buffer.append(',');
        buffer.append(data[i]);
      }
    }
  }

  private void appendUriArray(StringBuilder buffer, URI[] data) {
    if (data != null && data.length != 0) {
      buffer.append(data[0]);
      for(int i=1; i < data.length; i++) {
        buffer.append(',');
        buffer.append(data[i]);
      }
    }
  }

  private void dumpState(Configuration conf1) throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append("\nFiles:");
    appendUriArray(buf, DistributedCache.getCacheFiles(conf1));
    buf.append("\nArchives:");
    appendUriArray(buf, DistributedCache.getCacheArchives(conf1));
    buf.append("\nFile Visible:");
    appendBooleanArray(buf, TrackerDistributedCacheManager.getFileVisibilities
                      (conf1));
    buf.append("\nArchive Visible:");
    appendBooleanArray(buf, TrackerDistributedCacheManager.getArchiveVisibilities
                      (conf1));
    buf.append("\nFile timestamps:");
    appendLongArray(buf, DistributedCache.getFileTimestamps(conf1));
    buf.append("\nArchive timestamps:");
    appendLongArray(buf, DistributedCache.getArchiveTimestamps(conf1));
    LOG.info("state = " + buf.toString());
  }

  private void checkLocalizedPath(boolean visibility)
  throws IOException, LoginException, InterruptedException {
    TrackerDistributedCacheManager manager =
      new TrackerDistributedCacheManager(conf, taskController);
    String userName = getJobOwnerName();
    File workDir = new File(TEST_ROOT_DIR, "workdir");
    Path cacheFile = new Path(TEST_ROOT_DIR, "fourthcachefile");
    if (visibility) {
      createPublicTempFile(cacheFile);
    } else {
      createPrivateTempFile(cacheFile);
    }

    Configuration conf1 = new Configuration(conf);
    conf1.set("user.name", userName);
    DistributedCache.addCacheFile(cacheFile.toUri(), conf1);
    TrackerDistributedCacheManager.determineTimestamps(conf1);
    TrackerDistributedCacheManager.determineCacheVisibilities(conf1);
    dumpState(conf1);

    // Task localizing for job
    TaskDistributedCacheManager handle = manager
        .newTaskDistributedCacheManager(new JobID("jt", 1), conf1);
    handle.setupCache(conf1, TaskTracker.getPublicDistributedCacheDir(),
        TaskTracker.getPrivateDistributedCacheDir(userName));
    JobLocalizer.downloadPrivateCache(conf1);
    TaskDistributedCacheManager.CacheFile c = handle.getCacheFiles().get(0);
    String distCacheDir;
    if (visibility) {
      distCacheDir = TaskTracker.getPublicDistributedCacheDir();
    } else {
      distCacheDir = TaskTracker.getPrivateDistributedCacheDir(userName);
    }
    Path localizedPath =
      manager.getLocalCache(cacheFile.toUri(), conf1, distCacheDir,
                            fs.getFileStatus(cacheFile), false,
    		                c.timestamp, visibility, c);
    assertTrue("Cache file didn't get localized in the expected directory. " +
        "Expected localization to happen within " +
        ROOT_MAPRED_LOCAL_DIR + "/" + distCacheDir +
        ", but was localized at " +
        localizedPath, localizedPath.toString().contains(distCacheDir));
    if (visibility) {
      checkPublicFilePermissions(new Path[]{localizedPath});
    } else {
      checkFilePermissions(new Path[]{localizedPath});
    }
  }

  /**
   * Check proper permissions on the cache files
   *
   * @param localCacheFiles
   * @throws IOException
   */
  protected void checkFilePermissions(Path[] localCacheFiles)
      throws IOException {
    // All the files should have executable permissions on them.
    for (Path p : localCacheFiles) {
      assertTrue("Cache file is not executable!", new File(p
          .toUri().getPath()).canExecute());
    }
  }

  /**
   * Check permissions on the public cache files
   *
   * @param localCacheFiles
   * @throws IOException
   */
  private void checkPublicFilePermissions(Path[] localCacheFiles)
      throws IOException {
    checkPublicFilePermissions(fs, localCacheFiles);
  }

  /**
   * Verify the permissions for a file localized as a public distributed
   * cache file
   * @param fs The Local FileSystem used to get the permissions
   * @param localCacheFiles The list of files whose permissions should be
   * verified.
   * @throws IOException
   */
  public static void checkPublicFilePermissions(FileSystem fs,
      Path[] localCacheFiles) throws IOException {
    // All the files should have read and executable permissions for others
    for (Path p : localCacheFiles) {
      FsPermission perm = fs.getFileStatus(p).getPermission();
      assertTrue("cache file is not readable / executable by owner: perm="
          + perm.getUserAction(), perm.getUserAction()
          .implies(FsAction.READ_EXECUTE));
      assertTrue("cache file is not readable / executable by group: perm="
          + perm.getGroupAction(), perm.getGroupAction()
          .implies(FsAction.READ_EXECUTE));
      assertTrue("cache file is not readable / executable by others: perm="
          + perm.getOtherAction(), perm.getOtherAction()
          .implies(FsAction.READ_EXECUTE));
    }
  }

  /**
   * Verify the ownership for files localized as a public distributed cache
   * file.
   * @param fs The Local FileSystem used to get the ownership
   * @param localCacheFiles THe list of files whose ownership should be
   * verified
   * @param owner The owner of the files
   * @param group The group owner of the files.
   * @throws IOException
   */
  public static void checkPublicFileOwnership(FileSystem fs,
      Path[] localCacheFiles, String owner, String group)
      throws IOException {
    for (Path p: localCacheFiles) {
      assertEquals(owner, fs.getFileStatus(p).getOwner());
      assertEquals(group, fs.getFileStatus(p).getGroup());
    }
  }

  protected String getJobOwnerName() throws IOException {
    return UserGroupInformation.getLoginUser().getUserName();
  }

  /** test delete cache */
  public void testDeleteCache() throws Exception {
    if (!canRun()) {
      return;
    }
    // This test needs mapred.local.dir to be single directory
    // instead of four, because it assumes that both
    // firstcachefile and secondcachefile will be localized on same directory
    // so that second localization triggers deleteCache.
    // If mapred.local.dir is four directories, second localization might not
    // trigger deleteCache, if it is localized in different directory.
    Configuration conf2 = new Configuration(conf);
    conf2.set("mapred.local.dir", ROOT_MAPRED_LOCAL_DIR.toString());
    conf2.setLong("local.cache.size", LOCAL_CACHE_LIMIT);

    refreshConf(conf2);
    TrackerDistributedCacheManager manager =
        new TrackerDistributedCacheManager(conf2, taskController);
    FileSystem localfs = FileSystem.getLocal(conf2);
    long now = System.currentTimeMillis();
    String userName = getJobOwnerName();
    conf2.set("user.name", userName);

    // We first test the size limit
    FileStatus stat = fs.getFileStatus(firstCacheFilePublic);
    CacheFile cfile1 = new CacheFile(firstCacheFilePublic.toUri(),
    		                         CacheFile.FileType.REGULAR, true,
    		                         stat.getModificationTime(),
    		                         true);
    Path firstLocalCache = manager.getLocalCache(firstCacheFilePublic.toUri(), conf2,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(firstCacheFilePublic), false,
        fs.getFileStatus(firstCacheFilePublic).getModificationTime(), true,
        cfile1);
    manager.releaseCache(cfile1.getStatus());
    //in above code,localized a file of size 4K and then release the cache
    // which will cause the cache be deleted when the limit goes out.
    // The below code localize another cache which's designed to
    //sweep away the first cache.
    stat = fs.getFileStatus(secondCacheFilePublic);
    CacheFile cfile2 = new CacheFile(secondCacheFilePublic.toUri(),
    		                         CacheFile.FileType.REGULAR, true,
    		                         stat.getModificationTime(),
    		                         true);
    assertTrue("DistributedCache currently doesn't have cached file",
        localfs.exists(firstLocalCache));
    Path secondLocalCache = manager.getLocalCache(secondCacheFilePublic.toUri(), conf2,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(secondCacheFilePublic), false,
        fs.getFileStatus(secondCacheFilePublic).getModificationTime(), true,
        cfile2);
    assertFalse("DistributedCache failed deleting old" +
        " cache when the cache store is full.",
       localfs.exists(firstLocalCache));

    // find the root directory of distributed caches
    Path firstCursor = firstLocalCache;
    Path secondCursor = secondLocalCache;

    while (!firstCursor.equals(secondCursor)) {
      // Debug code, to see what these things look like
      System.err.println("cursors: " + firstCursor);
      System.err.println(" and " + secondCursor);

      firstCursor = firstCursor.getParent();
      secondCursor = secondCursor.getParent();
    }

    System.err.println("The final cursor is " + firstCursor);

    System.err.println("That directory ends up with "
                       + localfs.listStatus(firstCursor).length
                       + " subdirectories");
    Path cachesBase = firstCursor;

    assertFalse
      ("DistributedCache did not delete the gensym'ed distcache "
           + "directory names when it deleted the files they contained "
           + "because they collectively exceeded the size limit.",
       localfs.listStatus(cachesBase).length > 1);

    conf2.setLong("local.cache.size", LOCAL_CACHE_LIMIT * 10);
    conf2.setLong("mapreduce.tasktracker.local.cache.numberdirectories",
        LOCAL_CACHE_SUBDIR_LIMIT);
    manager =
      new TrackerDistributedCacheManager(conf2, taskController);
    // Now we test the number of sub directories limit
    // Create the temporary cache files to be used in the tests.
    Path thirdCacheFile = new Path(TEST_ROOT_DIR, "thirdcachefile");
    Path fourthCacheFile = new Path(TEST_ROOT_DIR, "fourthcachefile");
    // Adding two more small files, so it triggers the number of sub directory
    // limit but does not trigger the file size limit.
    createPrivateTempFile(thirdCacheFile);
    createPrivateTempFile(fourthCacheFile);
    DistributedCache.setCacheFiles(new URI[]{thirdCacheFile.toUri()}, conf2);
    TrackerDistributedCacheManager.determineCacheVisibilities(conf2);
    TrackerDistributedCacheManager.determineTimestamps(conf2);
    stat = fs.getFileStatus(thirdCacheFile);
    CacheFile cfile3 = new CacheFile(thirdCacheFile.toUri(),
            CacheFile.FileType.REGULAR, false,
            stat.getModificationTime(),
            true);
    Path thirdLocalCache = manager.getLocalCache(thirdCacheFile.toUri(), conf2,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(thirdCacheFile), false,
        fs.getFileStatus(thirdCacheFile).getModificationTime(),
        false, cfile3);
    DistributedCache.setLocalFiles(conf2, thirdLocalCache.toString());
    JobLocalizer.downloadPrivateCache(conf2);
    // Release the third cache so that it can be deleted while sweeping
    manager.releaseCache(cfile3.getStatus());
    // Getting the fourth cache will make the number of sub directories becomes
    // 3 which is greater than 2. So the released cache will be deleted.
    stat = fs.getFileStatus(fourthCacheFile);
    CacheFile cfile4 = new CacheFile(fourthCacheFile.toUri(),
            CacheFile.FileType.REGULAR, false,
            stat.getModificationTime(),
            true);
    assertTrue("DistributedCache currently doesn't have cached file",
        localfs.exists(thirdLocalCache));

    DistributedCache.setCacheFiles(new URI[]{fourthCacheFile.toUri()}, conf2);
    DistributedCache.setLocalFiles(conf2, thirdCacheFile.toUri().toString());
    TrackerDistributedCacheManager.determineCacheVisibilities(conf2);
    TrackerDistributedCacheManager.determineTimestamps(conf2);
    Path fourthLocalCache = manager.getLocalCache(fourthCacheFile.toUri(), conf2,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(fourthCacheFile), false,
        fs.getFileStatus(fourthCacheFile).getModificationTime(), false, cfile4);
    assertFalse("DistributedCache failed deleting old" +
        " cache when the cache exceeds the number of sub directories limit.",
        localfs.exists(thirdLocalCache));

    assertFalse
      ("DistributedCache did not delete the gensym'ed distcache "
           + "directory names when it deleted the files they contained "
           + "because there were too many.",
       localfs.listStatus(cachesBase).length > LOCAL_CACHE_SUBDIR_LIMIT);

    // Clean up the files created in this test
    new File(thirdCacheFile.toString()).delete();
    new File(fourthCacheFile.toString()).delete();
  }

  public void testFileSystemOtherThanDefault() throws Exception {
    if (!canRun()) {
      return;
    }
    TrackerDistributedCacheManager manager =
      new TrackerDistributedCacheManager(conf, taskController);
    conf.set("fs.fakefile.impl", conf.get("fs.file.impl"));
    String userName = getJobOwnerName();
    conf.set("user.name", userName);
    Path fileToCache = new Path("fakefile:///"
        + firstCacheFile.toUri().getPath());
    CacheFile file = new CacheFile(fileToCache.toUri(),
    		                       CacheFile.FileType.REGULAR,
    		                       false, 0, false);
    Path result = manager.getLocalCache(fileToCache.toUri(), conf,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(firstCacheFile), false,
        System.currentTimeMillis(),
        false, file);
    assertNotNull("DistributedCache cached file on non-default filesystem.",
        result);
  }

  static void createTempFile(Path p) throws IOException {
    createTempFile(p, TEST_FILE_SIZE);
  }

  static void createTempFile(Path p, int size) throws IOException {
    File f = new File(p.toString());
    FileOutputStream os = new FileOutputStream(f);
    byte[] toWrite = new byte[size];
    new Random().nextBytes(toWrite);
    os.write(toWrite);
    os.close();
    FileSystem.LOG.info("created: " + p + ", size=" + size);
  }

  static void createPublicTempFile(Path p)
  throws IOException, InterruptedException {
    createTempFile(p);
    FileUtil.chmod(p.toString(), "0777",true);
  }

  static void createPrivateTempFile(Path p)
  throws IOException, InterruptedException {
    createTempFile(p);
    FileUtil.chmod(p.toString(), "0770",true);
  }

  @Override
  protected void tearDown() throws IOException {
    new File(firstCacheFile.toString()).delete();
    new File(secondCacheFile.toString()).delete();
    new File(firstCacheFilePublic.toString()).delete();
    new File(secondCacheFilePublic.toString()).delete();
    FileUtil.fullyDelete(new File(TEST_ROOT_DIR));
  }

  protected void assertFileLengthEquals(Path a, Path b)
      throws FileNotFoundException {
    assertEquals("File sizes mismatch.",
       pathToFile(a).length(), pathToFile(b).length());
  }

  protected File pathToFile(Path p) {
    return new File(p.toString());
  }

  public static class FakeFileSystem extends RawLocalFileSystem {
    private long increment = 0;
    public FakeFileSystem() {
      super();
    }

    public FileStatus getFileStatus(Path p) throws IOException {
      File f = pathToFile(p);
      return new FileStatus(f.length(), f.isDirectory(), 1, 128,
      f.lastModified() + increment, makeQualified(new Path(f.getPath())));
    }

    void advanceClock(long millis) {
      increment += millis;
    }
  }

  public void testFreshness() throws Exception {
    if (!canRun()) {
      return;
    }
    Configuration myConf = new Configuration(conf);
    myConf.set("fs.default.name", "refresh:///");
    myConf.setClass("fs.refresh.impl", FakeFileSystem.class, FileSystem.class);
    String userName = getJobOwnerName();

    TrackerDistributedCacheManager manager =
      new TrackerDistributedCacheManager(myConf, taskController);
    // ****** Imitate JobClient code
    // Configures a task/job with both a regular file and a "classpath" file.
    Configuration subConf = new Configuration(myConf);
    subConf.set("user.name", userName);
    DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf);
    TrackerDistributedCacheManager.determineTimestamps(subConf);
    TrackerDistributedCacheManager.determineCacheVisibilities(subConf);
    // ****** End of imitating JobClient code

    // ****** Imitate TaskRunner code.
    TaskDistributedCacheManager handle =
      manager.newTaskDistributedCacheManager(new JobID("jt", 1), subConf);
    assertNull(null, DistributedCache.getLocalCacheFiles(subConf));
    File workDir = new File(new Path(TEST_ROOT_DIR, "workdir").toString());
    handle.setupCache(subConf, TaskTracker.getPublicDistributedCacheDir(),
        TaskTracker.getPrivateDistributedCacheDir(userName));
    //TODO this doesn't really happen in the TaskRunner
//    handle.setupPrivateCache(localDirAllocator, TaskTracker
//        .getPrivateDistributedCacheDir(userName));
    // ****** End of imitating TaskRunner code

    Path[] localCacheFiles = DistributedCache.getLocalCacheFiles(subConf);
    assertNotNull(null, localCacheFiles);
    assertEquals(1, localCacheFiles.length);
    Path cachedFirstFile = localCacheFiles[0];
    assertFileLengthEquals(firstCacheFile, cachedFirstFile);
    assertFalse("Paths should be different.",
        firstCacheFile.equals(cachedFirstFile));
    // release
    handle.release();

    // change the file timestamp
    FileSystem fs = FileSystem.get(myConf);
    ((FakeFileSystem)fs).advanceClock(1);

    // running a task of the same job
    Throwable th = null;
    try {
      handle.setupCache(subConf, TaskTracker.getPublicDistributedCacheDir(),
          TaskTracker.getPrivateDistributedCacheDir(userName));
//      handle.setupPrivateCache(localDirAllocator, TaskTracker
//          .getPrivateDistributedCacheDir(userName));
    } catch (IOException ie) {
      th = ie;
    }
    assertNotNull("Throwable is null", th);
    assertTrue("Exception message does not match",
        th.getMessage().contains("has changed on HDFS since job started"));
    // release
    handle.release();

    // submit another job
    Configuration subConf2 = new Configuration(myConf);
    subConf2.set("user.name", userName);
    DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf2);
    TrackerDistributedCacheManager.determineTimestamps(subConf2);
    TrackerDistributedCacheManager.determineCacheVisibilities(subConf2);

    handle =
      manager.newTaskDistributedCacheManager(new JobID("jt", 2), subConf2);
    handle.setupCache(subConf2, TaskTracker.getPublicDistributedCacheDir(),
        TaskTracker.getPrivateDistributedCacheDir(userName));
    Path[] localCacheFiles2 = DistributedCache.getLocalCacheFiles(subConf2);
    assertNotNull(null, localCacheFiles2);
    assertEquals(1, localCacheFiles2.length);
    Path cachedFirstFile2 = localCacheFiles2[0];
    assertFileLengthEquals(firstCacheFile, cachedFirstFile2);
    assertFalse("Paths should be different.",
        firstCacheFile.equals(cachedFirstFile2));

    // assert that two localizations point to different paths
    assertFalse("two jobs with different timestamps did not localize" +
        " in different paths", cachedFirstFile.equals(cachedFirstFile2));
    // release
    handle.release();
  }

  /**
   * Localize a file. After localization is complete, create a file, "myFile",
   * under the directory where the file is localized and ensure that it has
   * permissions different from what is set by default. Then, localize another
   * file. Verify that "myFile" has the right permissions.
   * @throws Exception
   */
  public void testCustomPermissions() throws Exception {
    if (!canRun()) {
      return;
    }
    String userName = getJobOwnerName();
    conf.set("user.name", userName);
    TrackerDistributedCacheManager manager =
        new TrackerDistributedCacheManager(conf, taskController);
    FileSystem localfs = FileSystem.getLocal(conf);
    long now = System.currentTimeMillis();

    Path[] localCache = new Path[2];
    FileStatus stat = fs.getFileStatus(firstCacheFile);
    CacheFile file = new CacheFile(firstCacheFilePublic.toUri(),
    		                       CacheFile.FileType.REGULAR, true,
    		                       stat.getModificationTime(), false);
    localCache[0] = manager.getLocalCache(firstCacheFilePublic.toUri(), conf,
        TaskTracker.getPrivateDistributedCacheDir(userName),
        fs.getFileStatus(firstCacheFilePublic), false,
        fs.getFileStatus(firstCacheFilePublic).getModificationTime(), true,
        file);
    FsPermission myPermission = new FsPermission((short)0600);
    Path myFile = new Path(localCache[0].getParent(), "myfile.txt");
    if (FileSystem.create(localfs, myFile, myPermission) == null) {
      throw new IOException("Could not create " + myFile);
    }
    try {
      stat = fs.getFileStatus(secondCacheFilePublic);
      file = new CacheFile(secondCacheFilePublic.toUri(),
    		               CacheFile.FileType.REGULAR,
    		               true, stat.getModificationTime(), false);
      localCache[1] = manager.getLocalCache(secondCacheFilePublic.toUri(), conf,
          TaskTracker.getPrivateDistributedCacheDir(userName),
          fs.getFileStatus(secondCacheFilePublic), false,
          fs.getFileStatus(secondCacheFilePublic).getModificationTime(), true,
          file);
      stat = localfs.getFileStatus(myFile);
      assertTrue(stat.getPermission().equals(myPermission));
      // validate permissions of localized files.
      checkFilePermissions(localCache);
    } finally {
      localfs.delete(myFile, false);
    }
  }

}


text:
title: Tip of the Day - MD5 Hash
description: "Transferring files, make sure to verify their integrity"
tags: [tutorial, md5, mac, linux]
comments: true
image:
  feature: texture-feature-01.jpg
---

When transferring files or making backups, be sure to create a hash of the file or files that you are operating on. This check ensures the integrity of the files you have been operating on are still intact once you are finished. There is built-in functionality to calculate and generate the hash value of MD5 without having to download and install additional program on most linux and unix based systems.

Mac example:

	md5 file_to_hash.txt

md5 will then print out a single line after calculating the hash:

* MD5(file_to_hash.txt)= bc0be71c056a7d7fad064fed72de46e1

Linux example:

	md5sum file_to_hash.txt

md5sum will then print out a single line after calculating the hash:

* bc0be71c056a7d7fad064fed72de46e1 file_to_hash.txt


text:
ancient
=======

Ancient projects I found on my hard drive which I couldn't bring myself to
delete.
 - android: 3 Android games I helped to create in a mobile programming class.
   This was for the very first G1 handset, so they are assuredly woefully out
   of date now.
 - Chomper: A Pacman clone which uses C++ and SDL.
 - CrazyBlocks: A tetris clone which uses SDL.
 - cryptogrammer: A cryptogtram generator which uses Ocaml and GTK+.
 - gfx: A set of small programs I created for a graphics class.  They all
   involve a 3D penguin.
 - Mandrill: The very first (awful) compiler I ever wrote for an independent
   study.  It compiles a language called Mandrill I invented down to MIPS
   assembly.
 - PowerBreakout: A breakout clone created with C++ and SDL.


text:
<?php

namespace rock\validate\locale\en;

use rock\validate\locale\Locale;

class FileSizeBetween extends Locale
{
    const BOTH = 0;
    const LOWER = 1;
    const GREATER = 2;

    public function defaultTemplates()
    {
        return  [
            self::MODE_DEFAULT => [
                self::BOTH => 'Size of {{name}} must be between {{minValue}} and {{maxValue}} bytes',
                self::LOWER => 'Size of {{name}}  must be greater than {{minValue}} bytes',
                self::GREATER => 'Size of {{name}} must be lower than {{maxValue}} bytes',
            ],
            self::MODE_NEGATIVE => [
                self::BOTH => 'Size of {{name}} must not be between {{minValue}} and {{maxValue}} bytes',
                self::LOWER => 'Size of {{name}}  must not be greater than {{minValue}} bytes',
                self::GREATER => 'Size of {{name}} must not be lower than {{maxValue}} bytes',
            ]
        ];
    }

    public function defaultPlaceholders($minValue = null, $maxValue = null)
    {
        if (!isset($minValue)) {
            $this->defaultTemplate = static::GREATER;
        } elseif (!isset($maxValue)) {
            $this->defaultTemplate = static::LOWER;
        } else {
            $this->defaultTemplate = static::BOTH;
        }

        return [
            'name' => 'file',
            'minValue' =>  $minValue,
            'maxValue' => $maxValue
        ];
    }
}


text:
#ifndef HKP_POINTTOPLANEDRAWER_H
#define HKP_POINTTOPLANEDRAWER_H

#include <Physics/Constraint/Visualize/Drawer/hkpConstraintDrawer.h>
#include <Physics/Constraint/Data/PointToPlane/hkpPointToPlaneConstraintData.h>

/// Displays information about the ballSocket constraint.
class HK_EXPORT_PHYSICS hkpPointToPlaneDrawer : public hkpConstraintDrawer
{
	public:

		HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HKP_MEMORY_CLASS_VDB, hkpPointToPlaneDrawer );

		void drawConstraint(const hkpPointToPlaneConstraintData* constraintData,
			const hkTransform& localToWorldA, const hkTransform& localToWorldB,
			hkDebugDisplayHandler* displayHandler, int id, int tag);
};

#endif	// HKP_POINTTOPLANEDRAWER_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
Vue.component('friend-list-item', {
    props: ['stream', 'shown'],
    data: function() {
        return {
            friendShown: false,
            videoReady: false,
            hover:false
        }
    },
    template: `

                <video autoplay="true" loop="true" @canplay="if(hover) { videoReady = true }" v-if="hover === true" v-show="videoReady === true" v-bind:src="channelVidUrl">
                </video>

                    {{stream.token}}
                    {{stream.viewersCurrent}}

                    {{channelGame}}

                    {{channelTitle}}

                <button class="btn btn-primary" v-on:click="addFriend" v-bind:data='channelToken' v-show="friendCheck(channelToken) === false">Add</button>
                <button class="btn btn-danger" v-on:click="removeFriend" v-bind:data='channelToken' v-show="friendCheck(channelToken)">Remove</button>

    `,
    methods:{
        addFriend: function(e){
            // This will add a friend to the list.
            var friend = e.target.attributes.data.value;
            this.$emit('add-friend', friend);
            this.friendShown = true;
        },
        removeFriend: function(e){
            // This will remove a friend from the list.
            var friend = e.target.attributes.data.value;
            this.$emit('remove-friend', friend);
            this.friendShown = false;
        },
        friendCheck: function(friend){
            // Checks to see if a friend is shown or not.
            let arr = this.shown;
            let obj = arr.find(o => o.token === friend);
            let index = arr.indexOf(obj);
            if(index > -1){
                return true
            } else {
                return false
            }
        }
    },
	computed: {
        channelChatUrl: function() {
            return `https://mixer.com/embed/chat/${this.stream.id}`;
        },
		channelImgUrl: function() {
			return `https://thumbs.mixer.com/channel/${this.stream.id}.small.jpg`;
		},
		channelVidUrl: function() {
			return `https://thumbs.mixer.com/channel/${this.stream.id}.m4v`;
		},
		channelLink: function(){
			return `https://mixer.com/${this.stream.token}`;
		},
		channelTitle: function(){
			return `${this.stream.name}`;
		},
		channelGame: function(){
			return `${this.stream.type.name}`;
        },
        channelToken: function(){
            return `${this.stream.token}`;
        }
	}
});

Vue.component('settings-modal', {
    props: ['username'],
    model:{
        user: null
    },
    template: `
        <transition name="modal">

Settings

                        <button class="modal-default-button btn btn-danger" @click="$emit('close')">
                            X
                        </button>

                                User

                                <input v-bind:value='username' placeholder="Firebottle" v-on:input="updateUserModel($event.target.value)">
                                <button class="btn btn-primary" @click='updateUsername'>Go!</button>

                                Online Friends
                                <button class="btn btn-primary" @click="$emit('add-all-friends')">Add All</button>

                                    <slot name="friendList"></slot>

        </transition>
    `,
    methods:{
        updateUsername: function(e){
            // This will add a friend to the list.
            this.$emit('update-username', this.user);
        },
        updateUserModel: function(newName){
            // This updates the component value to be passed on to main vue instance.
            this.user = newName;
        }
    },
	computed: {
        loggedInCheck: function() {
            // This checks if a user is logged in or not.
            if(this.username != null && this.username !== ''){
                return true;
            } else {
                return false;
            }
        }
	}
})


text:
/**
 * Persistence module
 *
 * (C) 2014 sequeldash
 */

module.exports = {
	plugin: null,
	__data: null,
	__watchers: [],

	watch: function(callback) {
		this.__watchers.push(callback);
	},

	_fireWatch: function(data) {
		for (var i = 0, max = this.__watchers.length; i < max; ++i) {
			var watcher = this.__watchers[i];
			watcher(data);
		}
	},

	/**
	 * Save the data onto the underlying storage mechanism.
	 * Defaults to localStorage unless plugin is defined.
	 *
	 * @param object data
	 * @return bool Whether successful
	 */
	save: function(data)
	{
		var self = this;
		if (!data)
			throw "You must pass the persisted data object";

		this.__data = data;

		(function() {
			if (this.plugin) {
				return this.plugin.persistData(data);
			} else {
				return new Promise(function(resolve, reject) {
					window.localStorage.sequeldash = JSON.stringify(data);
					resolve();
				});
			}
		})()
		.then(function() {
			self._fireWatch(data);
			return {error: '', message: 'Success'};
		})
		.catch(function(e) {
			alert('Error occurred while persisting data.');
			console.log('Error occurred while persisting data.');
			console.log(e);
		});
	},

	/**
	 * Retrieve the global persisted data. You can modify the object and that
	 * will be visible to all callers immediately, and persisted after
	 * next save().
	 */
	data: function()
	{
		if (this.plugin)
			return this.plugin.readData();

		var self = this;
		return new Promise(function(resolve, reject) {
			if (self.__data)
				resolve(self.__data);

			if (!window.localStorage) {
				console.log('Warning: No support/polyfill for localStorage. Filling with object.');
				window.localStorage = {};
			}

			if (!window.localStorage.sequeldash) {
				window.localStorage.sequeldash = "{}";
			}

			try {
				self.__data = JSON.parse(window.localStorage.sequeldash);

				if (self.__data == null) {
					window.localStorage.sequeldash = "{}";
					self.__data = {};
				}

			} catch (e) {
				self.__data = null;

				console.log('Failed to parse localStorage.sequeldash: ');
				console.log(window.localStorage.sequeldash);
				reject(e);
			}

			if (!self.__data)
				self.__data = {};

			resolve(self.__data);
		});
	}
};


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>

#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/platform_file.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/browser/fileapi/native_file_util.h"

namespace fileapi {

class NativeFileUtilTest : public testing::Test {
 public:
  NativeFileUtilTest() {}

  virtual void SetUp() {
    ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
  }

 protected:
  base::FilePath Path() {
    return data_dir_.path();
  }

  base::FilePath Path(const char* file_name) {
    return data_dir_.path().AppendASCII(file_name);
  }

  bool FileExists(const base::FilePath& path) {
    return base::PathExists(path) &&
           !base::DirectoryExists(path);
  }

  int64 GetSize(const base::FilePath& path) {
    base::PlatformFileInfo info;
    base::GetFileInfo(path, &info);
    return info.size;
  }

 private:
  base::ScopedTempDir data_dir_;

  DISALLOW_COPY_AND_ASSIGN(NativeFileUtilTest);
};

TEST_F(NativeFileUtilTest, CreateCloseAndDeleteFile) {
  base::FilePath file_name = Path("test_file");
  base::PlatformFile file_handle;
  bool created = false;
  int flags = base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_ASYNC;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateOrOpen(file_name,
                                         base::PLATFORM_FILE_CREATE | flags,
                                         &file_handle, &created));
  ASSERT_TRUE(created);

  EXPECT_TRUE(base::PathExists(file_name));
  EXPECT_TRUE(NativeFileUtil::PathExists(file_name));
  EXPECT_EQ(0, GetSize(file_name));
  EXPECT_NE(base::kInvalidPlatformFileValue, file_handle);

  ASSERT_EQ(base::PLATFORM_FILE_OK, NativeFileUtil::Close(file_handle));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateOrOpen(file_name,
                                         base::PLATFORM_FILE_OPEN | flags,
                                         &file_handle, &created));
  ASSERT_FALSE(created);
  ASSERT_EQ(base::PLATFORM_FILE_OK, NativeFileUtil::Close(file_handle));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::DeleteFile(file_name));
  EXPECT_FALSE(base::PathExists(file_name));
  EXPECT_FALSE(NativeFileUtil::PathExists(file_name));
}

TEST_F(NativeFileUtilTest, EnsureFileExists) {
  base::FilePath file_name = Path("foobar");
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(file_name, &created));
  ASSERT_TRUE(created);

  EXPECT_TRUE(FileExists(file_name));
  EXPECT_EQ(0, GetSize(file_name));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(file_name, &created));
  EXPECT_FALSE(created);
}

TEST_F(NativeFileUtilTest, CreateAndDeleteDirectory) {
  base::FilePath dir_name = Path("test_dir");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateDirectory(dir_name,
                                            false /* exclusive */,
                                            false /* recursive */));

  EXPECT_TRUE(NativeFileUtil::DirectoryExists(dir_name));
  EXPECT_TRUE(base::DirectoryExists(dir_name));

  ASSERT_EQ(base::PLATFORM_FILE_ERROR_EXISTS,
            NativeFileUtil::CreateDirectory(dir_name,
                                            true /* exclusive */,
                                            false /* recursive */));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::DeleteDirectory(dir_name));
  EXPECT_FALSE(base::DirectoryExists(dir_name));
  EXPECT_FALSE(NativeFileUtil::DirectoryExists(dir_name));
}

TEST_F(NativeFileUtilTest, TouchFileAndGetFileInfo) {
  base::FilePath file_name = Path("test_file");
  base::PlatformFileInfo native_info;
  ASSERT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::GetFileInfo(file_name, &native_info));

  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(file_name, &created));
  ASSERT_TRUE(created);

  base::PlatformFileInfo info;
  ASSERT_TRUE(base::GetFileInfo(file_name, &info));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::GetFileInfo(file_name, &native_info));
  ASSERT_EQ(info.size, native_info.size);
  ASSERT_EQ(info.is_directory, native_info.is_directory);
  ASSERT_EQ(info.is_symbolic_link, native_info.is_symbolic_link);
  ASSERT_EQ(info.last_modified, native_info.last_modified);
  ASSERT_EQ(info.last_accessed, native_info.last_accessed);
  ASSERT_EQ(info.creation_time, native_info.creation_time);

  const base::Time new_accessed =
      info.last_accessed + base::TimeDelta::FromHours(10);
  const base::Time new_modified =
      info.last_modified + base::TimeDelta::FromHours(5);

  EXPECT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::Touch(file_name,
                                  new_accessed, new_modified));

  ASSERT_TRUE(base::GetFileInfo(file_name, &info));
  EXPECT_EQ(new_accessed, info.last_accessed);
  EXPECT_EQ(new_modified, info.last_modified);
}

TEST_F(NativeFileUtilTest, CreateFileEnumerator) {
  base::FilePath path_1 = Path("dir1");
  base::FilePath path_2 = Path("file1");
  base::FilePath path_11 = Path("dir1").AppendASCII("file11");
  base::FilePath path_12 = Path("dir1").AppendASCII("dir12");
  base::FilePath path_121 =
      Path("dir1").AppendASCII("dir12").AppendASCII("file121");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateDirectory(path_1, false, false));
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(path_2, &created));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(path_11, &created));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateDirectory(path_12, false, false));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(path_121, &created));

  {
    scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> enumerator =
        NativeFileUtil::CreateFileEnumerator(Path(), false);
    std::set<base::FilePath> set;
    set.insert(path_1);
    set.insert(path_2);
    for (base::FilePath path = enumerator->Next(); !path.empty();
         path = enumerator->Next())
      EXPECT_EQ(1U, set.erase(path));
    EXPECT_TRUE(set.empty());
  }

  {
    scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> enumerator =
        NativeFileUtil::CreateFileEnumerator(Path(), true);
        std::set<base::FilePath> set;
    set.insert(path_1);
    set.insert(path_2);
    set.insert(path_11);
    set.insert(path_12);
    set.insert(path_121);
    for (base::FilePath path = enumerator->Next(); !path.empty();
         path = enumerator->Next())
      EXPECT_EQ(1U, set.erase(path));
    EXPECT_TRUE(set.empty());
  }
}

TEST_F(NativeFileUtilTest, Truncate) {
  base::FilePath file_name = Path("truncated");
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(file_name, &created));
  ASSERT_TRUE(created);

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::Truncate(file_name, 1020));

  EXPECT_TRUE(FileExists(file_name));
  EXPECT_EQ(1020, GetSize(file_name));
}

TEST_F(NativeFileUtilTest, CopyFile) {
  base::FilePath from_file = Path("fromfile");
  base::FilePath to_file1 = Path("tofile1");
  base::FilePath to_file2 = Path("tofile2");
  const NativeFileUtil::CopyOrMoveMode nosync = NativeFileUtil::COPY_NOSYNC;
  const NativeFileUtil::CopyOrMoveMode sync = NativeFileUtil::COPY_SYNC;
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(created);

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::Truncate(from_file, 1020));

  EXPECT_TRUE(FileExists(from_file));
  EXPECT_EQ(1020, GetSize(from_file));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file1, FileSystemOperation::OPTION_NONE, nosync));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file2, FileSystemOperation::OPTION_NONE, sync));

  EXPECT_TRUE(FileExists(from_file));
  EXPECT_EQ(1020, GetSize(from_file));
  EXPECT_TRUE(FileExists(to_file1));
  EXPECT_EQ(1020, GetSize(to_file1));
  EXPECT_TRUE(FileExists(to_file2));
  EXPECT_EQ(1020, GetSize(to_file2));

  base::FilePath dir = Path("dir");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateDirectory(dir, false, false));
  ASSERT_TRUE(base::DirectoryExists(dir));
  base::FilePath to_dir_file = dir.AppendASCII("file");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_dir_file,
                FileSystemOperation::OPTION_NONE, nosync));
  EXPECT_TRUE(FileExists(to_dir_file));
  EXPECT_EQ(1020, GetSize(to_dir_file));

  // Following tests are error checking.
  // Source doesn't exist.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                Path("nonexists"), Path("file"),
                FileSystemOperation::OPTION_NONE, nosync));

  // Source is not a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_A_FILE,
            NativeFileUtil::CopyOrMoveFile(
                dir, Path("file"), FileSystemOperation::OPTION_NONE, nosync));
  // Destination is not a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_INVALID_OPERATION,
            NativeFileUtil::CopyOrMoveFile(
                from_file, dir, FileSystemOperation::OPTION_NONE, nosync));
  // Destination's parent doesn't exist.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                from_file, Path("nodir").AppendASCII("file"),
                FileSystemOperation::OPTION_NONE, nosync));
  // Destination's parent is a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                from_file, Path("tofile1").AppendASCII("file"),
                FileSystemOperation::OPTION_NONE, nosync));
}

TEST_F(NativeFileUtilTest, MoveFile) {
  base::FilePath from_file = Path("fromfile");
  base::FilePath to_file = Path("tofile");
  const NativeFileUtil::CopyOrMoveMode move = NativeFileUtil::MOVE;
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(created);

  ASSERT_EQ(base::PLATFORM_FILE_OK, NativeFileUtil::Truncate(from_file, 1020));

  EXPECT_TRUE(FileExists(from_file));
  EXPECT_EQ(1020, GetSize(from_file));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file, FileSystemOperation::OPTION_NONE, move));

  EXPECT_FALSE(FileExists(from_file));
  EXPECT_TRUE(FileExists(to_file));
  EXPECT_EQ(1020, GetSize(to_file));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(FileExists(from_file));
  ASSERT_EQ(base::PLATFORM_FILE_OK, NativeFileUtil::Truncate(from_file, 1020));

  base::FilePath dir = Path("dir");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CreateDirectory(dir, false, false));
  ASSERT_TRUE(base::DirectoryExists(dir));
  base::FilePath to_dir_file = dir.AppendASCII("file");
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_dir_file,
                FileSystemOperation::OPTION_NONE, move));
  EXPECT_FALSE(FileExists(from_file));
  EXPECT_TRUE(FileExists(to_dir_file));
  EXPECT_EQ(1020, GetSize(to_dir_file));

  // Following is error checking.
  // Source doesn't exist.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                Path("nonexists"), Path("file"),
                FileSystemOperation::OPTION_NONE, move));

  // Source is not a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_A_FILE,
            NativeFileUtil::CopyOrMoveFile(
                dir, Path("file"), FileSystemOperation::OPTION_NONE, move));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(FileExists(from_file));
  // Destination is not a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_INVALID_OPERATION,
            NativeFileUtil::CopyOrMoveFile(
                from_file, dir, FileSystemOperation::OPTION_NONE, move));

  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(FileExists(from_file));
  // Destination's parent doesn't exist.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                from_file, Path("nodir").AppendASCII("file"),
                FileSystemOperation::OPTION_NONE, move));
  // Destination's parent is a file.
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND,
            NativeFileUtil::CopyOrMoveFile(
                from_file, Path("tofile1").AppendASCII("file"),
                FileSystemOperation::OPTION_NONE, move));
}

TEST_F(NativeFileUtilTest, PreserveLastModified) {
  base::FilePath from_file = Path("fromfile");
  base::FilePath to_file1 = Path("tofile1");
  base::FilePath to_file2 = Path("tofile2");
  base::FilePath to_file3 = Path("tofile3");
  bool created = false;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::EnsureFileExists(from_file, &created));
  ASSERT_TRUE(created);
  EXPECT_TRUE(FileExists(from_file));

  base::PlatformFileInfo file_info1;
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::GetFileInfo(from_file, &file_info1));

  // Test for copy (nosync).
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file1,
                FileSystemOperation::OPTION_PRESERVE_LAST_MODIFIED,
                NativeFileUtil::COPY_NOSYNC));

  base::PlatformFileInfo file_info2;
  ASSERT_TRUE(FileExists(to_file1));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::GetFileInfo(to_file1, &file_info2));
  EXPECT_EQ(file_info1.last_modified, file_info2.last_modified);

  // Test for copy (sync).
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file2,
                FileSystemOperation::OPTION_PRESERVE_LAST_MODIFIED,
                NativeFileUtil::COPY_SYNC));

  ASSERT_TRUE(FileExists(to_file2));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::GetFileInfo(to_file1, &file_info2));
  EXPECT_EQ(file_info1.last_modified, file_info2.last_modified);

  // Test for move.
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::CopyOrMoveFile(
                from_file, to_file3,
                FileSystemOperation::OPTION_PRESERVE_LAST_MODIFIED,
                NativeFileUtil::MOVE));

  ASSERT_TRUE(FileExists(to_file3));
  ASSERT_EQ(base::PLATFORM_FILE_OK,
            NativeFileUtil::GetFileInfo(to_file2, &file_info2));
  EXPECT_EQ(file_info1.last_modified, file_info2.last_modified);
}

}  // namespace fileapi


text: A public place to present Perlish playthings. Probably.


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\field\Unit\FieldConfigEntityUnitTest.
 */

namespace Drupal\Tests\field\Unit;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\field\Entity\FieldConfig
 * @group field
 */
class FieldConfigEntityUnitTest extends UnitTestCase {

  /**
   * The entity type used for testing.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityType;

  /**
   * The entity manager used for testing.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityManager;

  /**
   * The ID of the type of the entity under test.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * The UUID generator used for testing.
   *
   * @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $uuid;

  /**
   * The mock field storage.
   *
   * @var \Drupal\field\FieldStorageConfigInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $fieldStorage;

  /**
   * The typed configuration manager used for testing.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $typedConfigManager;

  /**
   * The mock field type plugin manager;
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $fieldTypePluginManager;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->entityTypeId = $this->randomMachineName();
    $this->entityType = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityTypeInterface');

    $this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');

    $this->uuid = $this->getMock('\Drupal\Component\Uuid\UuidInterface');

    $this->typedConfigManager = $this->getMock('Drupal\Core\Config\TypedConfigManagerInterface');

    $this->fieldTypePluginManager = $this->getMock('Drupal\Core\Field\FieldTypePluginManagerInterface');

    $container = new ContainerBuilder();
    $container->set('entity.manager', $this->entityManager);
    $container->set('uuid', $this->uuid);
    $container->set('config.typed', $this->typedConfigManager);
    $container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager);
    \Drupal::setContainer($container);

    // Create a mock FieldStorageConfig object.
    $this->fieldStorage = $this->getMock('\Drupal\field\FieldStorageConfigInterface');
    $this->fieldStorage->expects($this->any())
      ->method('getType')
      ->will($this->returnValue('test_field'));
    $this->fieldStorage->expects($this->any())
      ->method('getName')
      ->will($this->returnValue('field_test'));
    $this->fieldStorage->expects($this->any())
      ->method('getSettings')
      ->willReturn(array());
    // Place the field in the mocked entity manager's field registry.
    $this->entityManager->expects($this->any())
      ->method('getFieldStorageDefinitions')
      ->with('test_entity_type')
      ->will($this->returnValue(array(
        $this->fieldStorage->getName() => $this->fieldStorage,
      )));
  }

  /**
   * @covers ::calculateDependencies
   */
  public function testCalculateDependencies() {
    // Mock the interfaces necessary to create a dependency on a bundle entity.
    $bundle_entity = $this->getMock('Drupal\Core\Config\Entity\ConfigEntityInterface');
    $bundle_entity->expects($this->any())
      ->method('getConfigDependencyName')
      ->will($this->returnValue('test.test_entity_type.id'));

    $storage = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityStorageInterface');
    $storage->expects($this->any())
      ->method('load')
      ->with('test_bundle')
      ->will($this->returnValue($bundle_entity));

    $this->entityManager->expects($this->any())
      ->method('getStorage')
      ->with('bundle_entity_type')
      ->will($this->returnValue($storage));

    $target_entity_type = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
    $target_entity_type->expects($this->any())
      ->method('getBundleEntityType')
      ->will($this->returnValue('bundle_entity_type'));

    $this->entityManager->expects($this->at(0))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(1))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(2))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(3))
      ->method('getDefinition')
      ->with('test_entity_type')
      ->willReturn($target_entity_type);

    $this->fieldTypePluginManager->expects($this->any())
      ->method('getDefinition')
      ->with('test_field')
      ->willReturn(['provider' => 'test_module', 'config_dependencies' =>['module' => ['test_module2']], 'class' => '\Drupal\Tests\field\Unit\DependencyFieldItem']);

    $this->fieldStorage->expects($this->once())
      ->method('getConfigDependencyName')
      ->will($this->returnValue('field.storage.test_entity_type.test_field'));

    $field = new FieldConfig(array(
      'field_name' => $this->fieldStorage->getName(),
      'entity_type' => 'test_entity_type',
      'bundle' => 'test_bundle',
      'field_type' => 'test_field',
    ), $this->entityTypeId);
    $dependencies = $field->calculateDependencies();
    $this->assertContains('field.storage.test_entity_type.test_field', $dependencies['config']);
    $this->assertContains('test.test_entity_type.id', $dependencies['config']);
    $this->assertEquals(['test_module', 'test_module2', 'test_module3'], $dependencies['module']);
  }

  /**
   * Test that invalid bundles are handled.
   *
   * @expectedException \LogicException
   * @expectedExceptionMessage Missing bundle entity, entity type bundle_entity_type, entity id test_bundle_not_exists.
   */
  public function testCalculateDependenciesIncorrectBundle() {
    $storage = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityStorageInterface');
    $storage->expects($this->any())
      ->method('load')
      ->with('test_bundle_not_exists')
      ->will($this->returnValue(NULL));

    $this->entityManager->expects($this->any())
      ->method('getStorage')
      ->with('bundle_entity_type')
      ->will($this->returnValue($storage));

    $target_entity_type = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
    $target_entity_type->expects($this->any())
      ->method('getBundleEntityType')
      ->will($this->returnValue('bundle_entity_type'));

    $this->entityManager->expects($this->at(0))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(1))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(2))
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->willReturn($this->entityType);
    $this->entityManager->expects($this->at(3))
      ->method('getDefinition')
      ->with('test_entity_type')
      ->willReturn($target_entity_type);

    $this->fieldTypePluginManager->expects($this->any())
      ->method('getDefinition')
      ->with('test_field')
      ->willReturn(['provider' => 'test_module', 'config_dependencies' =>['module' => ['test_module2']], 'class' => '\Drupal\Tests\field\Unit\DependencyFieldItem']);

    $field = new FieldConfig(array(
      'field_name' => $this->fieldStorage->getName(),
      'entity_type' => 'test_entity_type',
      'bundle' => 'test_bundle_not_exists',
      'field_type' => 'test_field',
    ), $this->entityTypeId);
    $field->calculateDependencies();
  }

  /**
   * @covers ::toArray
   */
  public function testToArray() {
    $field = new FieldConfig(array(
      'field_name' => $this->fieldStorage->getName(),
      'entity_type' => 'test_entity_type',
      'bundle' => 'test_bundle',
      'field_type' => 'test_field',
    ), $this->entityTypeId);

    $expected = array(
      'id' => 'test_entity_type.test_bundle.field_test',
      'uuid' => NULL,
      'status' => TRUE,
      'langcode' => 'en',
      'field_name' => 'field_test',
      'entity_type' => 'test_entity_type',
      'bundle' => 'test_bundle',
      'label' => '',
      'description' => '',
      'required' => FALSE,
      'default_value' => array(),
      'default_value_callback' => '',
      'settings' => array(),
      'dependencies' => array(),
      'field_type' => 'test_field',
    );
    $this->entityManager->expects($this->any())
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->will($this->returnValue($this->entityType));
    $this->entityType->expects($this->once())
      ->method('getKey')
      ->with('id')
      ->will($this->returnValue('id'));
    $this->typedConfigManager->expects($this->once())
      ->method('getDefinition')
      ->will($this->returnValue(array('mapping' => array_fill_keys(array_keys($expected), ''))));

    $export = $field->toArray();
    $this->assertEquals($expected, $export);
  }

  /**
   * @covers ::getType
   */
  public function testGetType() {
    // Ensure that FieldConfig::getType() is not delegated to
    // FieldStorage.
    $this->entityManager->expects($this->never())
      ->method('getFieldStorageDefinitions');
    $this->fieldStorage->expects($this->never())
      ->method('getType');

    $field = new FieldConfig(array(
      'field_name' => $this->fieldStorage->getName(),
      'entity_type' => 'test_entity_type',
      'bundle' => 'test_bundle',
      'field_type' => 'test_field',
    ), $this->entityTypeId);

    $this->assertEquals('test_field', $field->getType());
  }

}

/**
 * A test class.
 *
 * @see \Drupal\Tests\field\Unit\FieldConfigEntityUnitTest::testCalculateDependencies()
 */
class DependencyFieldItem {

  public static function calculateDependencies(FieldDefinitionInterface $definition) {
    return ['module' => ['test_module3']];
  }

}


text:
package com.busqueumlugar.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.busqueumlugar.form.UsuarioForm;

@Controller
public class HomeController {

	private static final Logger log = LoggerFactory.getLogger(HomeController.class);

	@RequestMapping(value="/")
	public String test(HttpServletResponse response, ModelMap map) throws IOException{
		map.addAttribute("usuarioForm", new UsuarioForm());
		return "home";
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>api.mpdl.mpg.de</groupId>
	<artifactId>bio-formats-service</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>bio-formats-service</name>
	<description>Web service to for bio-formats library</description>
	<url>https://github.com/MPDL/bio-formats-service</url>
	<scm>
		<url>https://github.com/MPDL/bio-formats-service</url>
		<connection>scm:git:git://github.com/MPDL/bio-formats-service.git</connection>
		<developerConnection>scm:git:git@github.com:MPDL/bio-formats-service.git</developerConnection>
		<tag>master</tag>
	</scm>
	<issueManagement>
		<system>Github</system>
		<url>https://github.com/MPDL/bio-formats-service/issues</url>
	</issueManagement>
	<repositories>
		<repository>
			<id>nexus</id>
			<url>http://rd.mpdl.mpg.de/nexus/content/groups/public</url>
		</repository>
	</repositories>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
		<project.warName>bio-formats</project.warName>
	</properties>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warName>${project.warName}</warName>
					<outputDirectory>${tomcat.webapps}</outputDirectory>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<failIfNoTests>false</failIfNoTests>
					<additionalClasspathElements>
						<additionalClasspathElement>src/main/webapp/WEB-INF</additionalClasspathElement>
						<additionalClasspathElement>src/main/resources</additionalClasspathElement>
					</additionalClasspathElements>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>2.11</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>2.11</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-multipart</artifactId>
			<version>2.11</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
			<version>2.11</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-processing</artifactId>
			<version>2.11</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>17.0</version>
		</dependency>
		<!-- <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId>
			<version>1.0</version> </dependency> -->
		<dependency>
			<groupId>org.tuckey</groupId>
			<artifactId>urlrewritefilter</artifactId>
			<version>4.0.3</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.test-framework.providers</groupId>
			<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
			<version>2.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>openmicroscopy</groupId>
			<artifactId>bio-formats</artifactId>
			<version>5.0.5</version>
		</dependency>
	</dependencies>
</project>