text:
let app = angular.module('CAHOnline',['ngRoute','ngCookies','ngOrderObjectBy', 'ngAnimate', 'ngSanitize'])
app.factory('socket', function ($rootScope) {
  let socket = io('/')
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        let args = arguments
        $rootScope.$apply(function () {
          callback.apply(socket, args)
        })
      })
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        let args = arguments
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args)
          }
        })
      })
    },
    id: function(){
      return socket.io.engine.id
    },
    removeAllListeners: function() {
      socket.removeAllListeners()
    }
  }
})

app.config(function($routeProvider, $locationProvider) {
  $routeProvider
  .when("/", {
    templateUrl: "./templates/home.html",
    controller: "mainCtrl"
  })
  .when("/:room", {
    templateUrl: "./templates/game.html",
    controller: "joinGame"
  })

  $locationProvider.html5Mode(true)
})

app.controller("joinGame", function ($scope, $routeParams, $cookies, $timeout, $interval, $location, socket){
  $scope.room=$routeParams.room
  $scope.playerid=socket.id()

  /* Listeners */
  socket.on('first_load', function(data){
    $scope.playerid=socket.id()
    let lastId = $cookies.get("lastId")

    // if the user manually loaded a room page without going through the main menu,
    // we should kick him cause we cannot have his user infos
    if(!data.players[$scope.playerid] && !data.players[lastId]){
      $scope.isToKick = true;
      $timeout(function(){
        $location.path("/")
      }, 4000)
      return
    }

    // See if user refreshed the page (or lost connection and got reconnected)
    if(data.players[lastId] && data.players[lastId].room==$scope.room){
      //RECONNECT
      let playerObject = data.players[lastId]
      delete data.players[lastId]
      playerObject.id = $scope.playerid
      data.players[playerObject.id]=playerObject
      socket.emit('reconnect_player', {newPlayer: playerObject, oldPlayer: lastId})
      $scope.whiteCards = $cookies.getObject("whiteCards")
    }
    else{
      socket.emit('give_whitecards',{room: $scope.room, amount: 10})
    }
    $cookies.put("lastId",$scope.playerid)
    $scope.players=data.players
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
    $scope.gameState=data.gameState
    $scope.playedCards=[]
    $scope.myPlayedCards=[]
    $scope.time=30
  })

  // Wierd things can happen if only 2 people are playing (which shouldnt happen, but yea.)
  // TODO: See into this
  socket.on('waiting_room', function() {
    $scope.isWaitingRoom = true;
  });

  socket.on('display_players', function(data){
    $scope.players=data.players
    if(!$scope.iAmGameMaster && data.players[$scope.playerid].isGameMaster){
      $scope.showNewGameMaster=true
      $timeout(function(){
        $scope.showNewGameMaster=false
      },3000)
    }
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
  })

  socket.on('display_whitecards', function(data){
    $scope.whiteCards=data.whiteCards.concat($scope.whiteCards || [])
    $cookies.putObject("whiteCards",$scope.whiteCards)
  })

  socket.on('display_blackcard', function(data){
    $scope.blackCard = data.blackCard
  })

  let timer;
  socket.on('sync_gamestate', function(data){
    $scope.isWaitingRoom = false
    if(data.gameState == 1 && $scope.gameState != 3 && $scope.gameState != 0){
      $scope.skippingRound=true
      $timeout(function(){
        $scope.skippingRound=false
      },3000)
    }
    $scope.gameState=data.gameState

    switch(data.gameState){
      case 0:
        delete $scope.winner
        delete $scope.winnerCards
        $scope.myPlayedCards = new Array()
        $scope.playedCards = new Array()
        break
      case 1:
        delete $scope.winner
        delete $scope.winnerCards
        $scope.myPlayedCards = new Array()
        $scope.playedCards = new Array()
        socket.emit('give_whitecards', {room: $scope.room, amount: 10 - $scope.whiteCards.length})
        $scope.time=30
        $interval.cancel(timer)
        $timeout(function(){
          timer = $interval(function tick(){
            if($scope.time>0)
              $scope.time--
            else
              //Time is over so let's stop the timer here
              $interval.cancel(timer)
            return tick;
          }(),1000)
        }, 1)
        break
      case 2:
        break
      case 3:
        $scope.winner=data.args.winner
        $scope.winnerCards=data.args.winnerCards
        break
    }
  })

  socket.on('display_played_cards', function(data){
    $scope.playedCards=data.cards
  })

  /* Functions */

  $scope.startGame = function(){
    socket.emit('start_game',{room: $scope.room})
    $scope.showNewGameMaster=true
    $timeout(function(){
      $scope.showNewGameMaster=false
    },3000)
  }

  $scope.playCard = function(index){
    if(!$scope.myPlayedCards) $scope.myPlayedCards=[]
    $scope.myPlayedCards.push($scope.whiteCards[index])
    socket.emit("play_card",{text: $scope.whiteCards[index], player: $scope.playerid, room: $scope.room})
    $scope.whiteCards.splice(index,1)
    $cookies.putObject("whiteCards",$scope.whiteCards)
  }

  $scope.pickWinner = function(data){
    console.log("Il giocatore " + data.id + " ha giocato la/e carta/e più divertente/i: " + JSON.stringify(data.cards))
    if($scope.iAmGameMaster)  socket.emit('pick_winner', {room:$scope.room, winner:data.id, winnerCards:data.cards})
  }

  $scope.$on('$destroy', function (event) {
    socket.removeAllListeners()
  })

  /* Init */
  /* Should be called after all listeners, and maybe functions. */
  socket.emit('get_first_load',{room: $scope.room})
})

app.controller('mainCtrl', function($scope, $location, $cookies, $timeout, socket) {
  //if user clicked to go back to home we should remove him from the players, until he joins another room
  socket.emit("delete_player")
  $cookies.remove("lastId")

  $scope.createRoom = function() {
    let cbs = document.getElementsByClassName("set--mark");
    let sets = [];
    for(let i=0; i<cbs.length; i++){
      if(cbs[i].checked) sets.push(cbs[i].id.split("_").join(" "))
    }
    console.log(sets);
    if(sets.length < 1){
      $scope.setsWrong = true
      $timeout(function(){
        $scope.setsWrong = false
      },1000)
    }
    else
      socket.emit("create_room", {playerName: $scope.playerName, roomName: $scope.roomName, sets: sets})
  }

  $scope.joinRoom = function() {
    socket.emit("join_room", {
      playerName: $scope.playerName,
      roomId: $scope.roomId
    })
  }

  $scope.loadRooms = function(){
    socket.emit('get_rooms');
  }

  $scope.menuJoin = function(){
    if(!$scope.playerName || $scope.playerName.length <= 2){
      $scope.playerNameWrong = true
      $timeout(function(){
        $scope.playerNameWrong = false
      },2000)
    }
    else{
      $scope.loadRooms()
      $scope.homeIntro=!$scope.homeIntro
      $scope.homeJoinRoom=!$scope.homeJoinRoom
    }
  }

  $scope.menuCreate = function(){
    if(!$scope.playerName || $scope.playerName.length <= 2){
      $scope.playerNameWrong = true
      $timeout(function(){
        $scope.playerNameWrong = false
      },900)
    }
    else{
      $scope.homeIntro=!$scope.homeIntro
      $scope.homeCreateRoom=!$scope.homeCreateRoom
    }
  }

  socket.on('show_rooms', function(data){
    $scope.roomList = data.rooms
    $scope.roomCount = Object.keys(data.rooms).length;
  });

  $scope.getRoom = function(id){
    $scope.roomId = parseInt(id);
  }

  socket.on('load_game_page', function(data){
    $location.path("/"+data.room)
  })

  socket.on('show_sets', function(data){
    $scope.gameSets = data.sets;
  })
  socket.emit('get_sets');

  $scope.$on('$destroy', function (event) {
      socket.removeAllListeners()
      // or something like
      // socket.removeListener(this);
  })
})


text:
package org.zmpp.vm;

/**
 * This interface defines the Z machine's status line.
 *
 * @author Wei-ju Wu
 * @version 1.0
 */
public interface StatusLine {

    /**
     * Updates the status of a score game.
     *
     * @param objectName the object name
     * @param score the score
     * @param steps the number of steps
     */
    void updateStatusScore(String objectName, int score, int steps);

    /**
     * Updates the status of a time game.
     *
     * @param objectName the object name
     * @param hours the hours
     * @param minutes the minutes
     */
    void updateStatusTime(String objectName, int hours, int minutes);
}

redpajama_set_name: RedPajamaGithub


text:
Param(
    [ValidateSet('work', 'personal')]
    [string] $GitProfile
)

function EnsureFileStartsWithLine($LiteralPath, $Line) {
    if (Test-Path -LiteralPath $LiteralPath) {
        $Lines = @(Get-Content -LiteralPath $LiteralPath)
    } else {
        New-Item -Type Directory -Path (Split-Path $LiteralPath) -ErrorAction SilentlyContinue
        $Lines = @()
    }

    if ($Lines.Count -eq 0 -or $Lines[0] -ne $Line) {
        $Lines = @($Line) + $Lines
        $Lines | Out-File -LiteralPath $LiteralPath -Force
    }
}

$ProfileImpl = Join-Path $PSScriptRoot 'Profile.ps1';
EnsureFileStartsWithLine $global:profile ". $ProfileImpl"

$GitConfigImpl = (Join-Path $PSScriptRoot 'gitconfig_global.txt') -replace '\\','/';
EnsureFileStartsWithLine '~/.gitconfig' "[include] path = $GitConfigImpl";

if ($null -ne $env:WSL_INTEROP) {
    $GitConfigWslImpl = (Join-Path $PSScriptRoot 'gitconfig_global_wsl.txt') -replace '\\','/';
    EnsureFileStartsWithLine '~/.gitconfig' "[include] path = $GitConfigWslImpl";
}

$GitConfigProfileInfo = (Join-Path $PSScriptRoot "gitconfig_global_$($GitProfile).txt") -replace '\\','/';
EnsureFileStartsWithLine '~/.gitconfig' "[include] path = $($GitConfigProfileInfo)";


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Icon. fung. (Prague) 4: 32 (1840)

#### Original name
Dendryphiaceae Corda

### Remarks
null


text:
<?php
/**
 * @created Alexey Kutuzov <lexus27.khv@gmail.com>
 * @Project: php-abac
 */

namespace Jungle\ABAC\Generator;

class Rule{

}


text:
package com.amazonaws.services.emrserverless.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartJobRunRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ID of the application on which to run the job.
     *

     */
    private String applicationId;
    /**
     *

     * The client idempotency token of the job run to start. Its value must be unique for each request.
     *

     */
    private String clientToken;
    /**
     *

     * The execution role ARN for the job run.
     *

     */
    private String executionRoleArn;
    /**
     *

     * The job driver for the job run.
     *

     */
    private JobDriver jobDriver;
    /**
     *

     * The configuration overrides for the job run.
     *

     */
    private ConfigurationOverrides configurationOverrides;
    /**
     *

     * The tags assigned to the job run.
     *

     */
    private java.util.Map<String, String> tags;
    /**
     *

     * The maximum duration for the job run to run. If the job run runs beyond this duration, it will be automatically
     * cancelled.
     *

     */
    private Long executionTimeoutMinutes;
    /**
     *

     * The optional job run name. This doesn't have to be unique.
     *

     */
    private String name;

    /**
     *

     * The ID of the application on which to run the job.
     *

     *
     * @param applicationId
     *        The ID of the application on which to run the job.
     */

    public void setApplicationId(String applicationId) {
        this.applicationId = applicationId;
    }

    /**
     *

     * The ID of the application on which to run the job.
     *

     *
     * @return The ID of the application on which to run the job.
     */

    public String getApplicationId() {
        return this.applicationId;
    }

    /**
     *

     * The ID of the application on which to run the job.
     *

     *
     * @param applicationId
     *        The ID of the application on which to run the job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withApplicationId(String applicationId) {
        setApplicationId(applicationId);
        return this;
    }

    /**
     *

     * The client idempotency token of the job run to start. Its value must be unique for each request.
     *

     *
     * @param clientToken
     *        The client idempotency token of the job run to start. Its value must be unique for each request.
     */

    public void setClientToken(String clientToken) {
        this.clientToken = clientToken;
    }

    /**
     *

     * The client idempotency token of the job run to start. Its value must be unique for each request.
     *

     *
     * @return The client idempotency token of the job run to start. Its value must be unique for each request.
     */

    public String getClientToken() {
        return this.clientToken;
    }

    /**
     *

     * The client idempotency token of the job run to start. Its value must be unique for each request.
     *

     *
     * @param clientToken
     *        The client idempotency token of the job run to start. Its value must be unique for each request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withClientToken(String clientToken) {
        setClientToken(clientToken);
        return this;
    }

    /**
     *

     * The execution role ARN for the job run.
     *

     *
     * @param executionRoleArn
     *        The execution role ARN for the job run.
     */

    public void setExecutionRoleArn(String executionRoleArn) {
        this.executionRoleArn = executionRoleArn;
    }

    /**
     *

     * The execution role ARN for the job run.
     *

     *
     * @return The execution role ARN for the job run.
     */

    public String getExecutionRoleArn() {
        return this.executionRoleArn;
    }

    /**
     *

     * The execution role ARN for the job run.
     *

     *
     * @param executionRoleArn
     *        The execution role ARN for the job run.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withExecutionRoleArn(String executionRoleArn) {
        setExecutionRoleArn(executionRoleArn);
        return this;
    }

    /**
     *

     * The job driver for the job run.
     *

     *
     * @param jobDriver
     *        The job driver for the job run.
     */

    public void setJobDriver(JobDriver jobDriver) {
        this.jobDriver = jobDriver;
    }

    /**
     *

     * The job driver for the job run.
     *

     *
     * @return The job driver for the job run.
     */

    public JobDriver getJobDriver() {
        return this.jobDriver;
    }

    /**
     *

     * The job driver for the job run.
     *

     *
     * @param jobDriver
     *        The job driver for the job run.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withJobDriver(JobDriver jobDriver) {
        setJobDriver(jobDriver);
        return this;
    }

    /**
     *

     * The configuration overrides for the job run.
     *

     *
     * @param configurationOverrides
     *        The configuration overrides for the job run.
     */

    public void setConfigurationOverrides(ConfigurationOverrides configurationOverrides) {
        this.configurationOverrides = configurationOverrides;
    }

    /**
     *

     * The configuration overrides for the job run.
     *

     *
     * @return The configuration overrides for the job run.
     */

    public ConfigurationOverrides getConfigurationOverrides() {
        return this.configurationOverrides;
    }

    /**
     *

     * The configuration overrides for the job run.
     *

     *
     * @param configurationOverrides
     *        The configuration overrides for the job run.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withConfigurationOverrides(ConfigurationOverrides configurationOverrides) {
        setConfigurationOverrides(configurationOverrides);
        return this;
    }

    /**
     *

     * The tags assigned to the job run.
     *

     *
     * @return The tags assigned to the job run.
     */

    public java.util.Map<String, String> getTags() {
        return tags;
    }

    /**
     *

     * The tags assigned to the job run.
     *

     *
     * @param tags
     *        The tags assigned to the job run.
     */

    public void setTags(java.util.Map<String, String> tags) {
        this.tags = tags;
    }

    /**
     *

     * The tags assigned to the job run.
     *

     *
     * @param tags
     *        The tags assigned to the job run.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

    /**
     * Add a single Tags entry
     *
     * @see StartJobRunRequest#withTags
     * @returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest addTagsEntry(String key, String value) {
        if (null == this.tags) {
            this.tags = new java.util.HashMap<String, String>();
        }
        if (this.tags.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.tags.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into Tags.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest clearTagsEntries() {
        this.tags = null;
        return this;
    }

    /**
     *

     * The maximum duration for the job run to run. If the job run runs beyond this duration, it will be automatically
     * cancelled.
     *

     *
     * @param executionTimeoutMinutes
     *        The maximum duration for the job run to run. If the job run runs beyond this duration, it will be
     *        automatically cancelled.
     */

    public void setExecutionTimeoutMinutes(Long executionTimeoutMinutes) {
        this.executionTimeoutMinutes = executionTimeoutMinutes;
    }

    /**
     *

     * The maximum duration for the job run to run. If the job run runs beyond this duration, it will be automatically
     * cancelled.
     *

     *
     * @return The maximum duration for the job run to run. If the job run runs beyond this duration, it will be
     *         automatically cancelled.
     */

    public Long getExecutionTimeoutMinutes() {
        return this.executionTimeoutMinutes;
    }

    /**
     *

     * The maximum duration for the job run to run. If the job run runs beyond this duration, it will be automatically
     * cancelled.
     *

     *
     * @param executionTimeoutMinutes
     *        The maximum duration for the job run to run. If the job run runs beyond this duration, it will be
     *        automatically cancelled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withExecutionTimeoutMinutes(Long executionTimeoutMinutes) {
        setExecutionTimeoutMinutes(executionTimeoutMinutes);
        return this;
    }

    /**
     *

     * The optional job run name. This doesn't have to be unique.
     *

     *
     * @param name
     *        The optional job run name. This doesn't have to be unique.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The optional job run name. This doesn't have to be unique.
     *

     *
     * @return The optional job run name. This doesn't have to be unique.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The optional job run name. This doesn't have to be unique.
     *

     *
     * @param name
     *        The optional job run name. This doesn't have to be unique.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobRunRequest withName(String name) {
        setName(name);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getApplicationId() != null)
            sb.append("ApplicationId: ").append(getApplicationId()).append(",");
        if (getClientToken() != null)
            sb.append("ClientToken: ").append(getClientToken()).append(",");
        if (getExecutionRoleArn() != null)
            sb.append("ExecutionRoleArn: ").append(getExecutionRoleArn()).append(",");
        if (getJobDriver() != null)
            sb.append("JobDriver: ").append(getJobDriver()).append(",");
        if (getConfigurationOverrides() != null)
            sb.append("ConfigurationOverrides: ").append(getConfigurationOverrides()).append(",");
        if (getTags() != null)
            sb.append("Tags: ").append(getTags()).append(",");
        if (getExecutionTimeoutMinutes() != null)
            sb.append("ExecutionTimeoutMinutes: ").append(getExecutionTimeoutMinutes()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StartJobRunRequest == false)
            return false;
        StartJobRunRequest other = (StartJobRunRequest) obj;
        if (other.getApplicationId() == null ^ this.getApplicationId() == null)
            return false;
        if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false)
            return false;
        if (other.getClientToken() == null ^ this.getClientToken() == null)
            return false;
        if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
            return false;
        if (other.getExecutionRoleArn() == null ^ this.getExecutionRoleArn() == null)
            return false;
        if (other.getExecutionRoleArn() != null && other.getExecutionRoleArn().equals(this.getExecutionRoleArn()) == false)
            return false;
        if (other.getJobDriver() == null ^ this.getJobDriver() == null)
            return false;
        if (other.getJobDriver() != null && other.getJobDriver().equals(this.getJobDriver()) == false)
            return false;
        if (other.getConfigurationOverrides() == null ^ this.getConfigurationOverrides() == null)
            return false;
        if (other.getConfigurationOverrides() != null && other.getConfigurationOverrides().equals(this.getConfigurationOverrides()) == false)
            return false;
        if (other.getTags() == null ^ this.getTags() == null)
            return false;
        if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
            return false;
        if (other.getExecutionTimeoutMinutes() == null ^ this.getExecutionTimeoutMinutes() == null)
            return false;
        if (other.getExecutionTimeoutMinutes() != null && other.getExecutionTimeoutMinutes().equals(this.getExecutionTimeoutMinutes()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode());
        hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
        hashCode = prime * hashCode + ((getExecutionRoleArn() == null) ? 0 : getExecutionRoleArn().hashCode());
        hashCode = prime * hashCode + ((getJobDriver() == null) ? 0 : getJobDriver().hashCode());
        hashCode = prime * hashCode + ((getConfigurationOverrides() == null) ? 0 : getConfigurationOverrides().hashCode());
        hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
        hashCode = prime * hashCode + ((getExecutionTimeoutMinutes() == null) ? 0 : getExecutionTimeoutMinutes().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        return hashCode;
    }

    @Override
    public StartJobRunRequest clone() {
        return (StartJobRunRequest) super.clone();
    }

}


text: /* no problems in this javascript file */


text:
<?php
return ['Nombre'=>'Nombre'];
?>


text:
package com.feiyangedu.springcloud.petstore.common.filter;

import java.io.IOException;
import java.util.Base64;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feiyangedu.springcloud.petstore.common.context.UserContext;
import com.feiyangedu.springcloud.petstore.common.context.UserInfo;

public class UserContextFilter implements Filter {

	ObjectMapper objectMapper;

	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	final Log log = LogFactory.getLog(getClass());

	public UserContextFilter() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		UserInfo user = null;
		HttpServletRequest request = (HttpServletRequest) req;
		String auth = request.getHeader("Authorization");
		if (auth != null && auth.startsWith("Bearer ")) {
			String token = auth.substring(7);
			try {
				byte[] data = Base64.getUrlDecoder().decode(token);
				user = objectMapper.readValue(data, UserInfo.class);
				log.info("Parsed user: " + user);
			} catch (IllegalArgumentException | JsonParseException | JsonMappingException e) {
				log.warn("Parse token failed: " + token);
			}
		} else {
			log.info("Invalid Authorization header. set user = null.");
		}
		try (UserContext ctx = new UserContext(user)) {
			chain.doFilter(req, resp);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		log.info("Init UserContextFilter.");
	}

	@Override
	public void destroy() {
		log.info("Destroy UserContextFilter.");
	}

}


text:
package it.infn.ct;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.io.*;
import java.net.*;
import java.util.Set;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * CloudPovider class used to manage OCCI cloud endpoints for GridEngine
 * Job submission
 */
class CloudProvider {

    // Instantiate the logger object
    AppLogger _log = new AppLogger(CloudProvider.class);
    // Line separator
    public static final String LS = System.getProperty("line.separator");

    // DB settings
    String cloudprovider_dbname = "";
    String cloudprovider_dbhost = "";
    String cloudprovider_dbport = "";
    String cloudprovider_dbuser = "";
    String cloudprovider_dbpass = "";

    // Database variables
    private Connection connect = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;
    private String connectionURL = null;

    // Class activation flag; used by all methods
    boolean ebabled_class = false;

    String  proto;
    String  name;
    String  host;
    int     port;
    Map params = null;

    public boolean isEnabled() { return ebabled_class; }

    public CloudProvider(String cloudprovider_dbname
                        ,String cloudprovider_dbhost
                        ,String cloudprovider_dbport
                        ,String cloudprovider_dbuser
                        ,String cloudprovider_dbpass) {
        this.cloudprovider_dbname = cloudprovider_dbname;
        this.cloudprovider_dbhost = cloudprovider_dbhost;
        this.cloudprovider_dbport = cloudprovider_dbport;
        this.cloudprovider_dbuser = cloudprovider_dbuser;
        this.cloudprovider_dbpass = cloudprovider_dbpass;

        connectionURL="jdbc:mysql://" + cloudprovider_dbhost
                     +":"             + cloudprovider_dbport
                     +"/"             + cloudprovider_dbname
                     +"?user="        + cloudprovider_dbuser
                     +"&password="    + cloudprovider_dbpass;
        _log.info("connectionURL: '"+connectionURL+"'");

        if(!test_connection())
             _log.error("Unable to connect cloudprovider database; cloudprovider will be not available");
        else {
            _log.info("Successfully connected to iservices database; iservices will be available");
            ebabled_class = true;
        }
    }

    public CloudProvider(String name, String host, int port, String proto) {
        this.name  = name;
        this.host  = host;
        this.port  = port;
        this.proto = proto;
        // Initialize the rOCCI params map
        params = new HashMap();
    }

    // Add a single parameter to the cloud provider object
    public void addParam(String paramName, String paramValue) {
        if(params == null)
           params = new HashMap();
           params.put(paramName,paramValue);
    }

    // Add a set of params to the cloud provider object
    public void addParams(String params[][]) {
        if(params != null)
            for (int i=0; i<params.length; i++)
                addParam(params[i][0],params[i][1]);
    }

    // Build the cloud provider endpoint
    public String endPoint() {
        String endPoint = proto + "://"
                        + host  + ":"
                        + port  + "/?";
        int i = 0;
        Set set = params.keySet();
        Iterator iter = set.iterator();
        while (iter.hasNext()) {
            Object o = iter.next();
            String paramName = o.toString();
            String param = paramName + "=" + params.get(paramName);
            if (i == 0 ) i++;
            else param = "&"+param;
            endPoint+=param;
        }
        return endPoint;
    }

    public int geOperationId=-1;
    List<Integer> cloud_provider_ids = new ArrayList<Integer>();

    //
    // Database methods
    //
    public boolean test_connection() { return db_connect(); }
    public boolean db_connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection(connectionURL);
        } catch (Exception e) {
            _log.error(e.toString());
        }
        return (connect != null);
    }

    public void db_closeall() {
        try {
            if(resultSet         != null) { resultSet.close();         resultSet         = null; }
            if(statement         != null) { statement.close();         statement         = null; }
            if(preparedStatement != null) { preparedStatement.close(); preparedStatement = null; }
            if(connect           != null) { connect.close();           connect           = null; }
        } catch (Exception e) {
            _log.error(e.toString());
        }
    }

    public int getProviderList(int geOperationId) {
        int numCloudProviders = 0;
        String serviceDesc = "";
        if(!ebabled_class) return -1;
        if(!db_connect() ) return -1;
        if(geOperationId <= 0) return -1;
        this.geOperationId = geOperationId;
        cloud_provider_ids.clear();
        try {
            String query="select cp.id from cloud_provider_app cpa,cloud_provider cp where cpa.enabled is true and cp.enabled is true and ge_operation_id=? and cp.id=cpa.cloud_provider_id;";
            preparedStatement = connect.prepareStatement(query);
            preparedStatement.setInt(1,geOperationId);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()) {
              cloud_provider_ids.add(resultSet.getInt("cp.id"));
              numCloudProviders++;
            }
        } catch (SQLException e) {
            _log.error(e.toString());
        }
        db_closeall();
        return numCloudProviders;
    }

    public class CloudProviderInfo {
        public String name;
        public String host;
        public int    port;
        public String proto;

        public CloudProviderInfo(String name, String host, int port, String proto) {
            this.name = name;
            this.host = host;
            this.port = port;
            this.proto= proto;
        }
    };

    public CloudProviderInfo getCloudProviderInfo(int CloudProviderId) {
        CloudProviderInfo cpi = null;
        if(!ebabled_class) return null;
        if(CloudProviderId <= 0) return null;
        if(!db_connect() ) return null;
        try {
            String query="select name, address, port, proto from cloud_provider where id = ? and enabled is true;";
            preparedStatement = connect.prepareStatement(query);
            preparedStatement.setInt(1,CloudProviderId);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()) {
                cpi = new CloudProviderInfo(resultSet.getString("name")
                                           ,resultSet.getString("address")
                                           ,resultSet.getInt("port")
                                           ,resultSet.getString("proto")
                                          );
            }
        } catch (SQLException e) {
            _log.error(e.toString());
        }
        db_closeall();
        return cpi;
    }

    public String[][] getCloudProviderParams(int geOperationId, int CloudProviderId) {
        String cpParams[][] = null;
        int numParams = 0;
        if(!ebabled_class) return null;
        if(geOperationId <= 0) return null;
        if(CloudProviderId <= 0) return null;
        if(!db_connect() ) return null;
        String query = "";
        try {
            // Get param count first
            query="select count(*) from cloud_provider_params where ge_operation_id = ? and cloud_provider_id = ?;";
            preparedStatement = connect.prepareStatement(query);
            preparedStatement.setInt(1,geOperationId);
            preparedStatement.setInt(2,CloudProviderId);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()) {
                numParams = resultSet.getInt("count(*)");
            }
            cpParams = new String[numParams][2];
            // Get params
            query="select param_name, param_value from cloud_provider_params where ge_operation_id = ? and cloud_provider_id = ?;";
            preparedStatement = connect.prepareStatement(query);
            preparedStatement.setInt(1,geOperationId);
            preparedStatement.setInt(2,CloudProviderId);
            resultSet=preparedStatement.executeQuery();
            int i=0;
            while(resultSet.next()) {
                cpParams[i][0] = resultSet.getString("param_name");
                cpParams[i][1] = resultSet.getString("param_value");
                i++;
            }
        } catch (SQLException e) {
            _log.error(e.toString());
        }
        db_closeall();
        return cpParams;
    }

    public String[] getResourcesList() {
       String[] resourcesList = null;
       if(cloud_provider_ids.size() > 0) {
           resourcesList = new String[cloud_provider_ids.size()];
           // Now process the list
           Iterator iter = cloud_provider_ids.iterator();
           int i=0;
           while (iter.hasNext()) {
               int CloudProviderId=(Integer)iter.next();
               CloudProviderInfo cpi = getCloudProviderInfo(CloudProviderId);
               CloudProvider cp = new CloudProvider(cpi.name
                                                   ,cpi.host
                                                   ,cpi.port
                                                   ,cpi.proto);
               String params[][] = getCloudProviderParams(geOperationId,CloudProviderId);
               // Add OCCI parameters to the cloud provider object
               cp.addParams(params);
               String rOCCIURL = cp.endPoint();  _log.info("OCCI Endpoint: '" + rOCCIURL + "'");
               resourcesList[i] = rOCCIURL;
               i++;
           }
       }
       else _log.error("getResourcesList called with an empty resource list");
       return resourcesList;
    }

   //
   // Database methods for Infrastructure handling
   //
   public class Resource {
       int resource_id=-1;
       String name="";
       String address="";
       int port=-1;
       String proto="";
       boolean enabled=false;

       public Resource(int resource_id, String name, String address, int port, String proto, boolean enabled) {
          this.resource_id = resource_id;
          this.name = name;
          this.address = address;
          this.port = port;
          this.proto = proto;
          this.enabled = enabled;
       }

       HashMap<String,String> params = new HashMap<String,String>();

       public String getParam(String param_name) {
           return params.get(param_name);
       }

       public String getResourceEndpoint() {
           String endPoint = proto    + "://"
                           + address  + ":"
                           + port     + "/?";
           int i = 0;
           for (String param_name: params.keySet()) {
                String param_value = params.get(param_name);
                String param = param_name + "=" + param_value;
                if (i == 0 ) i++;
                else param = "&"+param;
                endPoint+=param;
           }
           return endPoint;
       }
   };
   public class Infrastructure {
       int     infrastructure_id=-1;
       String  name="";
       String  adaptor="";
       boolean enabled=false;

       public Infrastructure(int infrastructure_id, String name, String adaptor, boolean enabled) {
           this.infrastructure_id = infrastructure_id;
           this.name              = name;
           this.adaptor           = adaptor;
           this.enabled           = enabled;
       }

       HashMap<String,String> params = new HashMap<String,String>();
       List<Resource> resourcesList = new ArrayList<Resource>();

       public String[] resourceList() {
           String[] resList = new String[resourcesList.size()];
           for(int i=0; i<resourcesList.size(); i++) {
               resList[i] = resourcesList.get(i).getResourceEndpoint();
           }
           return resList;
       }

       public String getParam(String param_name) {
           return params.get(param_name);
       }
   };
   public List<Infrastructure> infrastructuresList = new ArrayList<Infrastructure>();

   // Biulds the classes above starting form the GridEngine application id
   public int AppInfrastructures(int geApplicationId) {
       if(!ebabled_class) return -1;
       if(geApplicationId <= 0) return -1;
       if(!db_connect() ) return -1;
       this.geOperationId = geOperationId;
       String query="";
       try {
            query="select i.id, i.name, i.adaptor, i.enabled and ia.enabled enabled from infrastructure_apps ia, infrastructures i where ge_operation_id = ? and i.id=ia.infrastructure_id;";
            preparedStatement = connect.prepareStatement(query);
            preparedStatement.setInt(1,geApplicationId);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()) {
                Infrastructure infrastructure = new Infrastructure( resultSet.getInt("i.id")
                                                                   ,resultSet.getString("i.name")
                                                                   ,resultSet.getString("i.adaptor")
                                                                   ,resultSet.getBoolean("enabled"));
                infrastructuresList.add(infrastructure);
            }
            // Now process infrastructures for params
            for(int i=0; i<infrastructuresList.size(); i++) {
                Infrastructure infra4params = (Infrastructure) infrastructuresList.get(i);
                query="select param_name, param_value from infrastructure_params where infrastructure_id = ?;";
                preparedStatement = connect.prepareStatement(query);
                preparedStatement.setInt(1,infra4params.infrastructure_id);
                resultSet=preparedStatement.executeQuery();
                while(resultSet.next()) {
                   String infra_param_name  = resultSet.getString("param_name" );
                   String infra_param_value = resultSet.getString("param_value");
                   infra4params.params.put(infra_param_name,infra_param_value);
                }
            }
            // Now process infrastructures for app resources
            for(int j=0; j<infrastructuresList.size(); j++) {
                Infrastructure infra4resources = (Infrastructure) infrastructuresList.get(j);
                query="select cp.id, cp.name, cp.address, cp.port, cp.proto, cp.enabled cp_enabled, ir.enabled ir_enabled  from cloud_provider cp, infrastructure_resources ir where cp.id=ir.cloud_provider_id and ir.infrastructure_id = ?;";
                preparedStatement = connect.prepareStatement(query);
                preparedStatement.setInt(1,infra4resources.infrastructure_id);
                resultSet=preparedStatement.executeQuery();
                while(resultSet.next()) {
                   Resource infraResource = new Resource(resultSet.getInt("cp.id")
                                                        ,resultSet.getString("cp.name")
                                                        ,resultSet.getString("cp.address")
                                                        ,resultSet.getInt("cp.port")
                                                        ,resultSet.getString("cp.proto")
                                                        ,resultSet.getBoolean("cp_enabled")
                                                        &resultSet.getBoolean("ir_enabled"));
                   infra4resources.resourcesList.add(infraResource);
                }
            }
            // Now process infrastructure resource parameters
            _log.info("Now adding resource parameters");
            for(int h=0; h<infrastructuresList.size(); h++) {
                Infrastructure infra4resparams = (Infrastructure) infrastructuresList.get(h);
                _log.info("  Infrastructure: " + infra4resparams.name);
                for(int k=0; k<infra4resparams.resourcesList.size(); k++) {
                    Resource resource4params = infra4resparams.resourcesList.get(k);
                    _log.info("    Now adding resource parameters for " + resource4params.name);
                    query="select param_name, param_value from cloud_provider_params where ge_operation_id=? and cloud_provider_id = ?;";
                    preparedStatement = connect.prepareStatement(query);
                    preparedStatement.setInt(1,geOperationId);
                    preparedStatement.setInt(2,resource4params.resource_id);
                    resultSet=preparedStatement.executeQuery();
                    while(resultSet.next()) {
                        String res_param_name  = resultSet.getString("param_name" );
                        String res_param_value = resultSet.getString("param_value");
                        resource4params.params.put(res_param_name,res_param_value);
                        _log.info("    (param_name = "+res_param_name+" - param_value = "+res_param_value+")");
                    }
                }
            }
        } catch (SQLException e) {
            _log.error(e.toString());
        }
        db_closeall();
        return infrastructuresList.size();
   }
};


text:
package com.tle.core.wizard.controls.universal.migration.v52;

import com.tle.core.guice.Bind;
import com.tle.core.migration.MigrationInfo;
import com.tle.core.wizard.controls.universal.migration.v50.FixIMSHandlerPath;
import javax.inject.Singleton;

/** @author Aaron */
@Bind
@Singleton
@SuppressWarnings("nls")
public class FixIMSHandlerPathRepeat extends FixIMSHandlerPath {
  @Override
  public MigrationInfo createMigrationInfo() {
    return new MigrationInfo(
        "com.tle.core.wizard.controls.universal.migration.associateattachments.imsfix.title", "");
  }
}


text:
@implementation MVSXMLRPCServiceBase

- (id)initWithBaseURL:(NSString *)aBaseURL {
    if ((self = [super initWithBaseURL:aBaseURL])) {
        // Initialization code here.
    }

    return self;
}

- (void)dealloc {
    [super dealloc];
}

- (NSXMLDocument *)documentForXMLRPCMethod:(NSString *)method paramDictionary:(NSDictionary *)dictionary methodID:(id)anID {
	NSXMLDocument *doc = [[NSXMLDocument alloc] initWithRootElement:[NSXMLNode elementWithName:@"methodCall"]];
	[doc addChild:[NSXMLNode elementWithName:@"methodName" stringValue:method]];

	return [doc autorelease];
}

- (NSXMLDocument *)documentForXMLNRPCMethod:(NSString *)method paramArray:(NSArray *)array methodID:(id)anID {
	NSXMLDocument *doc = [[NSXMLDocument alloc] initWithRootElement:[NSXMLNode elementWithName:@"methodCall"]];
	[doc addChild:[NSXMLNode elementWithName:@"methodName" stringValue:method]];

	return [doc autorelease];
}

- (void)dispatchRequest:(NSXMLDocument *)requestDoc callbackSelector:(SEL)selector delegate:(id<MVSWebserviceDelegate>)delegate clientCallbackSelector:(SEL)callback {

	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.baseURL]];
	[request setHTTPMethod:@"POST"];
	[request addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:[[requestDoc stringValue] dataUsingEncoding:NSUTF8StringEncoding]];

	if(self.asynchronous) {
		NSURLResponse *response = nil;
		NSError *error = nil;

		NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

		if(error != nil) {
			[delegate serviceDidReceiveError:self error:error];
		} else {
			NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
			NSInvocation *invocation = [self prepareInvocationForObject:self andSelector:selector];

			[invocation setArgument:&dataStr atIndex:2];
			[invocation setArgument:&delegate atIndex:3];
			[invocation setArgument:&callback atIndex:4];
			[invocation invoke];
			[dataStr release];
		}
	} else {
		MVSWebserviceOperation *op = [[MVSWebserviceOperation alloc] initWithURLRequest:request service:self selector:selector client:delegate callbackSelector:callback];

		[self addWebserviceOperation:op];
		[op release];
	}
}

@end


text:
package org.midnightbsd.appstore.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;

/**
 * @author Lucas Holt
 */
@Entity
@Table(name = "package")
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class Package implements Serializable {

    @JsonIgnore
    private static final long serialVersionUID = -1378527327884598865L;

    @Id
    @SequenceGenerator(name = "package_id_seq",
            sequenceName = "package_id_seq",
            allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = "package_id_seq")
    @Column(name = "id", updatable = false)
    private int id;

    @Column(name="name", nullable = false)
    private String name;

    @Column(name="description",columnDefinition="TEXT",length = 65616)
    private String description;

    @Column(name="url")
    private String url;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "package_category_map", joinColumns = @JoinColumn(name = "package_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "id"))
    private Set<Category> categories;

    @JsonIgnore
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "pkg", fetch = FetchType.LAZY)
    private Set<Rating> ratings;

    @JsonManagedReference(value = "package-instance")
    @JsonProperty("instances")
    @OneToMany(cascade = { CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}, mappedBy = "pkg", fetch = FetchType.EAGER)
    private Set<PackageInstance> instances;

    @JsonIgnore
    @Column(name = "created")
    @Temporal(value = TemporalType.DATE)
    private Date created = new Date();
}


text:
title: 9-03-17
layout: post
author: anshu.attavar
permalink: /9-03-17/
source-id: 1wQQX_2qBveq2J6vTnZKyfrpHuh5aUIIYbIpMPcvaz4A
published: true
---
Hey Guys. Todays lesson was quite fun as I finally figured out what the code which I was working on last week does. You put lights on the breadboard and then you put some wires and resistors to the sockets and the lights light up in this weird pattern. I think if you change the code you can possibly change the pattern of the bulbs lighting up. See you next week.


text:
<?php
namespace Procure\Application\Command\PO;

use Application\Application\Command\AbstractDoctrineCmd;
use Application\Domain\Shared\Command\AbstractCommandHandler;
use Application\Domain\Shared\Command\CommandInterface;
use Procure\Application\Command\PO\Options\PoAmendmentEnableOptions;
use Procure\Application\Command\PO\Options\PoUpdateOptions;
use Procure\Application\Service\SharedServiceFactory;
use Procure\Domain\Contracts\ProcureDocStatus;
use Procure\Domain\Exception\DBUpdateConcurrencyException;
use Procure\Domain\Exception\InvalidArgumentException;
use Procure\Domain\Exception\OperationFailedException;
use Procure\Domain\Exception\PoInvalidOperationException;
use Procure\Domain\PurchaseOrder\PODoc;
use Procure\Domain\PurchaseOrder\POSnapshot;
use Procure\Infrastructure\Doctrine\POQueryRepositoryImpl;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class EnableAmendmentCmdHandler extends AbstractCommandHandler
{

    /**
     *
     * {@inheritdoc}
     * @see \Application\Application\Command\AbstractDoctrineCmdHandler::run()
     */
    public function run(CommandInterface $cmd)
    {
        if (! $cmd instanceof AbstractDoctrineCmd) {
            throw new \Exception(sprintf("% not foundsv!", "AbstractDoctrineCmd"));
        }

        /**
         *
         * @var PODoc $rootEntity ;
         * @var POSnapshot $rootSnapshot ;
         * @var PoUpdateOptions $options ;
         *
         */
        $options = $cmd->getOptions();

        if (! $options instanceof PoAmendmentEnableOptions) {
            throw new InvalidArgumentException("No Options given. Pls check command configuration!");
        }

        $options = $cmd->getOptions();

        $rootEntity = $options->getRootEntity();
        $rootEntityId = $options->getRootEntityId();
        $version = $options->getVersion();

        if (! $rootEntity->getDocStatus() == ProcureDocStatus::POSTED) {
            throw new PoInvalidOperationException(sprintf("PO is not signed and posted! %s", $rootEntity->getId()));
        }

        try {
            /**
             *
             * @var POSnapshot $snapshot ;
             * @var POSnapshot $rootSnapshot ;
             * @var PODoc $rootEntity ;
             */
            $sharedService = SharedServiceFactory::createForPO($cmd->getDoctrineEM());
            $rootEntity->enableAmendment($options, $sharedService);
            // event dispatch
            // ================
            if ($cmd->getEventBus() !== null) {
                $cmd->getEventBus()->dispatch($rootEntity->getRecordedEvents());
            }
            // ================

            $queryRep = new POQueryRepositoryImpl($cmd->getDoctrineEM());

            // time to check version - concurency
            $currentVersion = $queryRep->getVersion($rootEntityId) - 1;

            // revision numner has been increased.
            if ($version != $currentVersion) {
                throw new DBUpdateConcurrencyException(sprintf("Object has been changed from %s to %s since retrieving. Please retry! ", $version, $currentVersion));
            }
        } catch (\Exception $e) {

            throw new OperationFailedException($e->getMessage());
        }
    }
}


text:
#ifndef SICERT_H
#define SICERT_H

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmsign/sitypes.h"

#ifdef WITH_OPENSSL

#include "dcmtk/ofstd/ofstring.h"   /* for class OFString */

class DcmItem;
class SiAlgorithm;
struct x509_st;
typedef struct x509_st X509;

/** a class representing X.509 public key certificates.
 */
class DCMTK_DCMSIGN_EXPORT SiCertificate
{
public:

  /// default constructor
  SiCertificate();

  ///destructor
  virtual ~SiCertificate();

  /** loads an X.509 certificate from file.
   *  @param filename file name of X.509 certificate
   *  @param filetype file format: X509_FILETYPE_PEM or X509_FILETYPE_ASN1
   *  @return status code
   */
  OFCondition loadCertificate(const char *filename, int filetype);

  /** reads an X.509 certificate from an item of the Digital Signatures Sequence
   *  and checks the certificate type information in the item.
   *  @param item item of the DigitalSignatureSQ from which the certificate is read
   *  @return status code
   */
  OFCondition read(DcmItem& item);

  /** writes the current X.509 certificate into an item of the Digital Signatures Sequence
   *  and creates the certificate type information in the item.
   *  @param item item of the DigitalSignatureSQ to which the certificate is written
   *  @return dcmdata OFCondition status code
   */
  OFCondition write(DcmItem& item);

  /** returns the type of public key stored in this certificate
   */
  E_KeyType getKeyType();

  /** creates an SiAlgorithm object for the public key contained in this certificate.
   *  If no certificate loaded or operation fails, returns NULL.
   *  New SiAlgorithm object must be deleted by caller.
   *  @return pointer to new SiAlgorithm object
   */
  SiAlgorithm *createAlgorithmForPublicKey();

  /** returns the format version of the X.509 certificate.
   *  If no certificate is loaded, returns 0.
   *  @return X.509 certificate version
   */
  long getX509Version();

  /** returns the subject name (distinguished name) of the current certificate.
   *  If no certificate is loaded, returns an empty string.
   *  @param str subject name returned in this string.
   */
  void getCertSubjectName(OFString& str);

  /** returns the issuer name (distinguished name) of the current certificate.
   *  If no certificate is loaded, returns an empty string.
   *  @param str issuer name returned in this string.
   */
  void getCertIssuerName(OFString& str);

  /** returns the serial number of the X.509 certificate.
   *  If no certificate is loaded, returns -1.
   *  @return X.509 certificate serial number
   */
  long getCertSerialNo();

  /** returns the start of validity of the current certificate in human readable form.
   *  If no certificate is loaded, returns an empty string.
   *  @param str start of validity returned in this string.
   */
  void getCertValidityNotBefore(OFString& str);

  /** returns the end of validity of the current certificate in human readable form.
   *  If no certificate is loaded, returns an empty string.
   *  @param str end of validity returned in this string.
   */
  void getCertValidityNotAfter(OFString& str);

  /** returns the strength (number of bits) of the public key contained
   *  in the current certificate.
   *  If no certificate is loaded, returns 0.
   *  @return key strength in bits.
   */
  long getCertKeyBits();

  /** returns a pointer to the raw certificate structure or NULL if no
   *  certificate present. Should not be called by users of this library.
   */
  X509 *getRawCertificate();

private:

  /// private undefined copy constructor
  SiCertificate(SiCertificate& arg);

  /// private undefined copy assignment operator
  SiCertificate& operator=(SiCertificate& arg);

  /// OpenSSL X.509 structure
  X509* x509;

};

#endif
#endif