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

package app.metatron.discovery.domain.user;

import app.metatron.discovery.common.CommonLocalVariable;
import app.metatron.discovery.common.GlobalObjectMapper;
import app.metatron.discovery.common.Mailer;
import app.metatron.discovery.common.StatLogger;
import app.metatron.discovery.common.entity.SearchParamValidator;
import app.metatron.discovery.common.exception.BadRequestException;
import app.metatron.discovery.common.exception.ResourceNotFoundException;
import app.metatron.discovery.domain.images.Image;
import app.metatron.discovery.domain.images.ImageService;
import app.metatron.discovery.domain.user.group.Group;
import app.metatron.discovery.domain.user.group.GroupMember;
import app.metatron.discovery.domain.user.group.GroupService;
import app.metatron.discovery.domain.user.org.OrganizationService;
import app.metatron.discovery.domain.user.role.RoleRepository;
import app.metatron.discovery.domain.user.role.RoleService;
import app.metatron.discovery.domain.user.role.RoleSetRepository;
import app.metatron.discovery.domain.user.role.RoleSetService;
import app.metatron.discovery.domain.workspace.Workspace;
import app.metatron.discovery.domain.workspace.WorkspaceMemberRepository;
import app.metatron.discovery.domain.workspace.WorkspaceService;
import app.metatron.discovery.util.AuthUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.querydsl.core.types.Predicate;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static app.metatron.discovery.domain.user.UserService.DuplicatedTarget.EMAIL;
import static app.metatron.discovery.domain.user.UserService.DuplicatedTarget.USERNAME;

/**
 *
 */
@RepositoryRestController
public class UserController {

  private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

  @Autowired
  RoleService roleService;

  @Autowired
  GroupService groupService;

  @Autowired
  OrganizationService orgService;

  @Autowired
  RoleSetService roleSetService;

  @Autowired
  WorkspaceService workspaceService;

  @Autowired
  ImageService imageService;

  @Autowired
  UserRepository userRepository;

  @Autowired
  WorkspaceMemberRepository workspaceMemberRepository;

  @Autowired
  RoleRepository roleRepository;

  @Autowired
  RoleSetRepository roleSetRepository;

  @Autowired
  ProjectionFactory projectionFactory;

  @Autowired
  CachedUserService cachedUserService;

  @Autowired
  PagedResourcesAssembler pagedResourcesAssembler;

  @Autowired
  UserService userService;

  @Autowired
  JdbcClientDetailsService jdbcClientDetailsService;

  @Autowired
  Mailer mailer;

  @Autowired
  PasswordEncoder passwordEncoder;

  @Autowired
  UserProperties userProperties;

  /**
   * User 목록 조회
   */
  @RequestMapping(path = "/users", method = RequestMethod.GET)
  public ResponseEntity<?> findUsers(@RequestParam(value = "level", required = false) String level,
          @RequestParam(value = "active", required = false) Boolean active,
          @RequestParam(value = "status", required = false) List<String> status,
          @RequestParam(value = "nameContains", required = false) String nameContains,
          @RequestParam(value = "searchDateBy", required = false) String searchDateBy,
          @RequestParam(value = "from", required = false)
          @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime from,
          @RequestParam(value = "to", required = false)
          @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime to,
          Pageable pageable, PersistentEntityResourceAssembler resourceAssembler) {

    List<User.Status> reqStatus = null;
    if (CollectionUtils.isNotEmpty(status)) {
      reqStatus = Lists.newArrayList();
      for (String s : status) {
        reqStatus.add(SearchParamValidator.enumUpperValue(User.Status.class, s, "status"));
      }
    }

    // Get Predicate
    Predicate searchPredicated = UserPredicate
            .searchList(level, active, reqStatus, nameContains, searchDateBy, from, to);

    // 기본 정렬 조건 셋팅
    if (pageable.getSort() == null || !pageable.getSort().iterator().hasNext()) {
      pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(),
              new Sort(Sort.Direction.ASC, "fullName"));
    }

    Page<User> users = userRepository.findAll(searchPredicated, pageable);

    return ResponseEntity.ok(this.pagedResourcesAssembler.toResource(users, resourceAssembler));

  }

  /**
   * User 상세 조회
   */
  @RequestMapping(path = "/users/{username:.+}", method = RequestMethod.GET)
  public ResponseEntity<?> findDetailUser(@PathVariable("username") String username,
          PersistentEntityResourceAssembler resourceAssembler) {

    User user = userRepository.findByUsername(username);
    if (user == null) {
      return ResponseEntity.notFound().build();
    }

    return ResponseEntity.ok(resourceAssembler.toResource(user));

  }

  /**
   * User 삭제
   */
  @Transactional
  @PreAuthorize("authentication.name == #username or hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/{username:.+}", method = RequestMethod.DELETE)
  public ResponseEntity<?> deleteUser(@PathVariable("username") String username) {

    User user = userRepository.findByUsername(username);
    if (user == null) {
      return ResponseEntity.notFound().build();
    }

    userRepository.delete(user);

    // Delete images related with the user
    if (StringUtils.isNotEmpty(user.getImageUrl())) {
      imageService.deleteImage(Image.DOMAIN_USER, user.getId());
    }

    // Delete created workspaces, and leave joined workspaces
    workspaceService.deleteWorkspaceAndMember(user.getUsername());

    // Delete the member in joined groups
    groupService.deleteGroupMember(user.getUsername());

    // Delete the member of organizations
    orgService.deleteOrgMembers(user.getUsername());

    // Delete if there is user information stored in the cache
    cachedUserService.removeCachedUser(user.getUsername());

    return ResponseEntity.noContent().build();
  }

  /**
   * User 자신에 의해 사용자 정보 수정
   */
  @Transactional
  @PreAuthorize("authentication.name == #username")
  @RequestMapping(path = "/users/{username:.+}", method = RequestMethod.PATCH)
  public ResponseEntity<?> updateUser(@PathVariable("username") String username, @RequestBody User user) {

    User updatedUser = userRepository.findByUsername(username);
    if (updatedUser == null) {
      throw new ResourceNotFoundException(username);
    }

    if (!username.equals(AuthUtils.getAuthUserName())) {
      throw new UserException("Fail to update permission. only user(" + username + ") can update.");
    }

    if (user.getPassword() != null) {
      //check password changed
      if (!passwordEncoder.matches(updatedUser.getPassword(), user.getPassword())) {
        //if config minimum password change date exist..
        if (StringUtils.isNotEmpty(userProperties.getPassword().getMinimumUsePeriod())) {
          //parse to period
          Period minimumUsePeriod = Period.parse(userProperties.getPassword().getMinimumUsePeriod());
          LOGGER.debug("minimumUsePeriod : {}", minimumUsePeriod);

          //getting last update datetime
          DateTime passwordChangedDate = userService.getLastPasswordUpdatedDate(username);
          LOGGER.debug("{}'s passwordChangedDate : {}", username, passwordChangedDate);
          if (minimumUsePeriod != null && passwordChangedDate != null) {

            //must user password period
            DateTime mustUsePasswordDate = passwordChangedDate.plus(minimumUsePeriod);
            LOGGER.debug("{} must use password to {}", username, mustUsePasswordDate);
            if (DateTime.now().getMillis() < mustUsePasswordDate.getMillis()) {
              //user cannot update password
              LOGGER.debug("{} cannot change password.", username);
              throw new UserException(UserErrorCodes.PASSWORD_USE_PERIOD_NOT_PASSED,
                      "The minimum password usage period has not passed.(" + mustUsePasswordDate + ")");
            }
          }
        }

        //check password validation
        userService.validateUserPassword(username, user);

        //check matched previous password
        userService.getMatchedPreviousPassword(username, user.getPassword());

        String encodedPassword = passwordEncoder.encode(user.getPassword());
        updatedUser.setPassword(encodedPassword);
      }
    }

    if (user.getFullName() != null) {
      updatedUser.setFullName(user.getFullName());
    }
    if (user.getEmail() != null) {
      updatedUser.setEmail(user.getEmail());
    }
    if (user.getTel() != null) {
      updatedUser.setTel(user.getTel());
    }
    if (user.getImageUrl() != null) {
      if (StringUtils.isBlank(user.getImageUrl())) {
        userService.deleteUserImage(updatedUser.getUsername());
        updatedUser.setImageUrl(null);
      } else {
        userService.updateUserImage(updatedUser.getUsername());
        updatedUser.setImageUrl(user.getImageUrl());
      }
    }

    userRepository.saveAndFlush(updatedUser);

    // user 정보 갱신
    updatedUser.setRoleService(roleService);
    AuthUtils.refreshAuth(updatedUser);
    cachedUserService.removeCachedUser(username);

    // Workspace Member 이름 갱신
    workspaceMemberRepository.updateMemberName(updatedUser.getUsername(), updatedUser.getFullName());

    return ResponseEntity.ok(updatedUser);

  }

  /**
   * 사용자 가입 요청
   */
  @RequestMapping(path = "/users/signup", method = RequestMethod.POST)
  public ResponseEntity<?> createUserBySignup(@RequestBody User user) {

    // Check if username is duplicate
    if (userService.checkDuplicated(USERNAME, user.getUsername())) {
      throw new UserException(UserErrorCodes.DUPLICATED_USERNAME_CODE, "Duplicated username : " + user.getUsername());
    }

    // Check if e-mail is duplicate
    if (userService.checkDuplicated(EMAIL, user.getEmail())) {
      throw new UserException(UserErrorCodes.DUPLICATED_EMAIL_CODE, "Duplicated e-mail : " + user.getEmail());
    }

    //password expr check
    userService.validateUserPassword(user.getUsername(), user);

    // check user org code if exist
    if(user.getOrgCodes() != null && user.getOrgCodes().size() > 0) {
      for(String orgCode : user.getOrgCodes()){
        if(!orgService.checkDuplicatedCode(orgCode)){
          throw new UserException(UserErrorCodes.ORGANIZATION_NOT_VALID, "Not valid Org Code : " + orgCode);
        }
      }

      user.setRequestOrgCodes(GlobalObjectMapper.writeValueAsString(user.getOrgCodes()));
    }

    if (StringUtils.isBlank(user.getFullName())) {
      user.setFullName(user.getUsername());
    }

    if (StringUtils.isNotBlank(user.getImageUrl())) {
      userService.updateUserImage(user.getUsername());
    }

    if (user.getPassword() != null) {
      String encodedPassword = passwordEncoder.encode(user.getPassword());
      user.setPassword(encodedPassword);
    }

    if(user.getPassApprove()){
      userService.approveSignupRequest(user);
      userRepository.save(user);
    } else {
      user.setStatus(User.Status.REQUESTED);
      userRepository.save(user);
      mailer.sendSignUpRequestMail(user, false);
    }

    return ResponseEntity.created(URI.create("")).build();
  }

  /**
   * 최초 접속시 패스워드 수정
   */
  @RequestMapping(path = "/users/password", method = RequestMethod.POST)
  public ResponseEntity<?> updateInitialUser(@RequestBody User user) {

    User updatedUser = userRepository.findByUsername(user.getUsername());
    if (updatedUser == null) {
      throw new ResourceNotFoundException(user.getUsername());
    }

    if (!(User.Status.INITIAL.equals(updatedUser.getStatus()) || User.Status.EXPIRED.equals(updatedUser.getStatus()))) {
      throw new UserException("Fail to update password. Only for initial access or expired users.");
    }

    if (!passwordEncoder.matches(user.getInitialPassword(), updatedUser.getPassword())) {
      throw new UserException(UserErrorCodes.INITIAL_PASSWORD_NOT_MATCHED,
              "Fail to update password. It does not match the initial password.");
    }

    updatedUser.setStatus(User.Status.ACTIVATED);
    if (user.getPassword() != null) {
      userService.validateUserPassword(user.getUsername(), user);
      String encodedPassword = passwordEncoder.encode(user.getPassword());
      updatedUser.setPassword(encodedPassword);
    }

    userRepository.saveAndFlush(updatedUser);

    return ResponseEntity.ok(updatedUser);

  }

  /**
   * 관리자용 사용자 등록
   */
  @Transactional
  @PreAuthorize("hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/manual", method = RequestMethod.POST)
  public ResponseEntity<?> createUserByAdmin(@RequestBody User user) {

    String userEmail = user.getEmail();

    // Check if username is duplicate
    if (userService.checkDuplicated(USERNAME, user.getUsername())) {
      throw new UserException(UserErrorCodes.DUPLICATED_USERNAME_CODE, "Duplicated username : " + user.getUsername());
    }

    // Check if e-mail is duplicate
    if (StringUtils.isNotEmpty(userEmail) && userService.checkDuplicated(EMAIL, user.getEmail())) {
      throw new UserException(UserErrorCodes.DUPLICATED_EMAIL_CODE, "Duplicated e-mail : " + user.getEmail());
    }

    if (StringUtils.isBlank(user.getFullName())) {
      user.setFullName(user.getUsername());
    }

    if (StringUtils.isNotBlank(user.getImageUrl())) {
      userService.updateUserImage(user.getUsername());
    }

    // If password is not specified without mail transmission, the system generates password
    if (!user.getPassMailer() || StringUtils.isEmpty(user.getPassword())) {
      String temporaryPassword = userService.createTemporaryPassword(user.getUsername());
      user.setPassword(temporaryPassword);

      StatLogger.generateTempPassword("User Creation", user.getUsername(), temporaryPassword);
    }

    //encode password
    String decryptedPassword = user.getPassword();
    String encodedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encodedPassword);

    user.setStatus(User.Status.ACTIVATED);

    // If there is no group information, specify the default group
    if (CollectionUtils.isNotEmpty(user.getGroupNames())) {
      userService.setUserToGroups(user, user.getGroupNames());
    } else {
      Group defaultGroup = groupService.getDefaultGroup();
      if (defaultGroup == null) {
        LOGGER.warn("Default group not found.");
      } else {
        defaultGroup.addGroupMember(new GroupMember(user.getUsername(), user.getFullName()));
      }
    }

    // Create Workspace (create if there is no registered workspace)
    Workspace createdWorkspace = workspaceService.createWorkspaceByUserCreation(user, false);

    userRepository.save(user);

    // Add Organization
    String orgCode = CommonLocalVariable.getLocalVariable().getTenantAuthority().getOrgCode();
    orgService.addMembers(Lists.newArrayList(orgCode), user.getUsername(), user.getFullName(), DirectoryProfile.Type.USER);

    if (!user.getPassMailer()) {
      mailer.sendSignUpApprovedMail(user, true, decryptedPassword);
    }

    Map<String, Object> responseMap = Maps.newHashMap();
    responseMap.put("username", user.getUsername());
    responseMap.put("privateWorkspace", "/api/workspaces/" + createdWorkspace.getId());

    return ResponseEntity.created(URI.create("")).body(responseMap);
  }

  /**
   * 관리자용 사용자 정보 업데이트
   */
  @Transactional
  @PreAuthorize("hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/{username}/manual", method = RequestMethod.PUT)
  public ResponseEntity<?> updateUserByAdmin(@PathVariable("username") String username, @RequestBody User user) {

    User updatedUser = userRepository.findByUsername(username);

    if (updatedUser == null) {
      return ResponseEntity.notFound().build();
    }

    if(user.getGroupNames() != null && user.getGroupNames().size() > 0){
      userService.setUserToGroups(updatedUser, user.getGroupNames());
    }

    if (StringUtils.isNotBlank(user.getFullName())) {
      updatedUser.setFullName(user.getFullName());
    }

    if (StringUtils.isNotBlank(user.getEmail())) {
      updatedUser.setEmail(user.getEmail());
    }

    if (StringUtils.isNotBlank(user.getTel())) {
      updatedUser.setTel(user.getTel());
    }

    if (StringUtils.isBlank(user.getImageUrl()) && StringUtils.isNotBlank(updatedUser.getImageUrl())) {
      userService.deleteUserImage(updatedUser.getUsername());
      updatedUser.setImageUrl(null);
    }

    if (StringUtils.isNotBlank(user.getImageUrl())) {
      userService.updateUserImage(username);
      updatedUser.setImageUrl(user.getImageUrl());
    }

    updatedUser.setStatus(User.Status.ACTIVATED);
    if (user.getPassword() != null) {
      userService.validateUserPassword(username, user);
      String encodedPassword = passwordEncoder.encode(user.getPassword());
      updatedUser.setPassword(encodedPassword);
    }

    userRepository.saveAndFlush(updatedUser);

    // user 정보 갱신
    if (AuthUtils.getAuthUserName().equals(updatedUser.getUsername())) {
      updatedUser.setRoleService(roleService);
      AuthUtils.refreshAuth(updatedUser);
    }

    // Cache 저장 정보 갱신
    cachedUserService.removeCachedUser(username);

    // Workspace Member 이름 갱신
    workspaceMemberRepository.updateMemberName(updatedUser.getUsername(), updatedUser.getFullName());

    return ResponseEntity.ok(updatedUser);
  }

  /**
   * reset password (include sending temporary password by email)
   *
   * @param additionalInfo email, client id
   * @param locale  Browser locale
   * @return
   */
  @RequestMapping(path = "/users/password/reset", method = RequestMethod.POST)
  public ResponseEntity<?> resetPassword(@RequestBody Map<String, Object> additionalInfo, Locale locale) {

    if (!additionalInfo.containsKey("email")) {
      throw new BadRequestException("E-mail address required");
    }

    String email = (String) additionalInfo.get("email");
    User user = userRepository.findByEmail(email);
    if (user == null) {
      throw new BadRequestException("User not found by email( " + email + " )");
    }

    String temporaryPassword = userService.createTemporaryPassword(user.getUsername());
    String encodedPassword = passwordEncoder.encode(temporaryPassword);
    user.setPassword(encodedPassword);
    StatLogger.generateTempPassword("Rest Password", user.getUsername(), temporaryPassword);

    user.setStatus(User.Status.INITIAL);
    user.setFailCnt(null);

    userRepository.saveAndFlush(user);

    boolean isAdmin = false;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
      isAdmin = true;
    }

    ClientDetails client = null;
    String clientId = (String) additionalInfo.getOrDefault("clientId", "");
    if(StringUtils.isNotEmpty(clientId)) {
      client = jdbcClientDetailsService.loadClientByClientId(clientId);
    }

    mailer.sendPasswordResetMail(user, client, temporaryPassword, isAdmin, locale);

    return ResponseEntity.noContent().build();
  }

  @RequestMapping(path = "/users/password/validate", method = RequestMethod.POST)
  public ResponseEntity<?> validatePassword(@RequestBody User user) {

    if (StringUtils.isNotEmpty(user.getInitialPassword())) {
      User updatedUser = userRepository.findByUsername(user.getUsername());
      if (updatedUser == null) {
        throw new ResourceNotFoundException(user.getUsername());
      } else if (!passwordEncoder.matches(user.getInitialPassword(), updatedUser.getPassword())) {
        throw new UserException(UserErrorCodes.INITIAL_PASSWORD_NOT_MATCHED,
                "Fail to update password. It does not match the initial password.");
      }
    } else {
      userService.validatePassword(user.getUsername(), user.getPassword());
    }

    return ResponseEntity.ok(true);
  }

  /**
   * @param username
   * @param additionalInfo
   * @return
   */
  @RequestMapping(path = "/users/{username}/check/password", method = RequestMethod.POST)
  public ResponseEntity<?> checkPassword(@PathVariable("username") String username,
          @RequestBody Map<String, Object> additionalInfo) {

    if (!additionalInfo.containsKey("password")) {
      throw new BadRequestException("password required");
    }

    String password = (String) additionalInfo.get("password");
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new ResourceNotFoundException(username);
    }

    Map<String, Boolean> matched = Maps.newHashMap();
    matched.put("matched", passwordEncoder.matches(password, user.getPassword()));

    return ResponseEntity.ok(matched);
  }

  /**
   * @param target
   * @param value
   * @return
   */
  @RequestMapping(path = "/users/{target}/{value}/duplicated", method = RequestMethod.GET)
  public ResponseEntity<?> checkDuplicatedValue(@PathVariable("target") String target,
          @PathVariable("value") String value) {

    UserService.DuplicatedTarget targetType = SearchParamValidator
            .enumUpperValue(UserService.DuplicatedTarget.class, target, "target");

    Map<String, Boolean> duplicated = Maps.newHashMap();
    duplicated.put("duplicated", userService.checkDuplicated(targetType, value));

    return ResponseEntity.ok(duplicated);

  }

  /**
   * 가입 승인
   */
  @Transactional
  @PreAuthorize("hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/{username}/approved", method = RequestMethod.POST)
  public ResponseEntity<?> approvedJoinedUser(@PathVariable("username") String username) {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new ResourceNotFoundException(username);
    }

    userService.approveSignupRequest(user);

    return ResponseEntity.noContent().build();
  }

  /**
   * 가입 승인 반려
   */
  @PreAuthorize("hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/{username}/rejected", method = RequestMethod.POST)
  public ResponseEntity<?> rejectedJoinedUser(@PathVariable("username") String username,
          @RequestBody Map<String, Object> additionalInfo) {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new ResourceNotFoundException(username);
    }

    user.setStatus(User.Status.REJECTED);
    user.setStatusMessage((String) additionalInfo.get("message"));

    userRepository.save(user);

    mailer.sendSignUpDeniedMail(user);

    return ResponseEntity.noContent().build();
  }

  /**
   * 사용자 상태 변경, 관리자(사용자 변경) 권한만 처리 가능
   */
  @PreAuthorize("hasAuthority('PERM_SYSTEM_MANAGE_USER')")
  @RequestMapping(path = "/users/{username}/status/{status}", method = RequestMethod.POST)
  public ResponseEntity<?> changeStatus(@PathVariable("username") String username,
          @PathVariable("status") String status) {

    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new ResourceNotFoundException(username);
    }

    User.Status reqStatus = SearchParamValidator
            .enumUpperValue(User.Status.class, status, "status");

    switch (reqStatus) {
      case ACTIVATED:
        if (user.getStatus() == User.Status.ACTIVATED) {
          throw new UserException("Already activated user.");
        }
        user.setFailCnt(null);
        user.setStatus(User.Status.ACTIVATED);
        break;
      case LOCKED:
        if (user.getStatus() == User.Status.LOCKED) {
          throw new RuntimeException("Already inactivated user.");
        }
        user.setStatus(User.Status.LOCKED);
        break;
      case DELETED:
        if (user.getStatus() == User.Status.DELETED) {
          throw new RuntimeException("Already deleted user.");
        }
        user.setStatus(User.Status.DELETED);

        // 캐시에 저장되어 있는 User 정보가 있다면 삭제
        cachedUserService.removeCachedUser(user.getUsername());
        break;
      default:
        throw new BadRequestException("Unsupported status. choose 'activate' or 'locked'");
    }

    userRepository.save(user);

    return ResponseEntity.noContent().build();
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta content="text/html; charset=utf-8" http-equiv="content-type" />
        <meta content="en-us" http-equiv="Content-Language" />
        <link rel="stylesheet" type="text/css" href="fonts.css" />
        <title>Preview</title>

            InriaSans-Light : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

            InriaSans-LightItalic : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

            InriaSans-Italic : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

            InriaSans-Regular : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

            InriaSans-Bold : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

            InriaSans-BoldItalic : The quick brown fox jumps over the lazy dog. $123.45!
firedogs Paphlagonia striped dying
possibility scurrile lipsalve viaticals

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

void TestDeleteChar() {
	char * str = new char[1];
	str += 2;
	delete[] str;
}

void TestDeleteInt() {
	int * arr = new int[0];
	delete[] arr;
}

int main()
{
	TestDeleteChar();
	TestDeleteInt();
	system("pause");
	return 0;
}


text:
set -e

# You can run it from any directory.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Execute common pre-setup, include test functions.
# shellcheck disable=SC1090
source "$DIR/common.sh"

printTestStarted

# Create several files that should be synced to remote machine.
mkdir "$BUILD_DIR/src"
touch "$BUILD_DIR/src/file1.txt"
touch "$BUILD_DIR/src/file2.txt"
touch "$BUILD_DIR/src/file3.txt"

# Run mainframer that creates "build" result file that should be synced back to local machine.
# shellcheck disable=SC2016
"$MAINFRAMER_EXECUTABLE" 'mkdir build && for ((i=0;i<30;i++)); do dd if=/dev/urandom of=build/buildresult-$i.txt bs=16M count=4 iflag=fullblock; sleep 1; done; ls -la build'

for ((i=0;i<30;i++)); do
    # Make sure files exist on local machine after sync.
    localFileMustMatchRemote "build/buildresult-$i.txt" "(sync problem)"
done

printTestEnded


text:
require "m9t"

require "metar/data"

# References:
# WMO = World Meteorological Organization Manual on Codes Volume I.1
#   Section FM 15

module Metar
  class Parser
    def self.for_cccc(cccc)
      raw = Metar::Raw::Noaa.new(cccc)
      new(raw)
    end

    COMPLIANCE = %i(strict loose).freeze

    def self.thread_attributes
      Thread.current[:metar_parser] ||= {}
    end

    def self.compliance
      thread_attributes[:compliance] ||= :loose
    end

    def self.compliance=(compliance)
      raise 'Unknown compliance' unless COMPLIANCE.find(compliance)

      thread_attributes[:compliance] = compliance
    end

    attr_reader :raw
    attr_reader :metar
    attr_reader :observer
    attr_reader :wind
    attr_reader :variable_wind
    attr_reader :visibility
    attr_reader :minimum_visibility
    attr_reader :runway_visible_range
    attr_reader :present_weather
    attr_reader :sky_conditions
    attr_reader :vertical_visibility
    attr_reader :temperature_and_dew_point
    attr_reader :sea_level_pressure
    attr_reader :recent_weather
    attr_reader :unparsed
    attr_reader :remarks

    def initialize(raw)
      @raw   = raw
      @metar = raw.metar.clone
      analyze
    end

    def station_code
      @station_code.value
    end

    def time
      @time.value
    end

    def cavok?
      @cavok
    end

    def temperature
      return nil if @temperature_and_dew_point.nil?

      @temperature_and_dew_point.temperature
    end

    def dew_point
      return nil if @temperature_and_dew_point.nil?

      @temperature_and_dew_point.dew_point
    end

    def raw_attributes
      attr = {
        metar: metar,
        datetime: @time.raw,
        station_code: station_code
      }
      %i(
        minimum_visibility
        observer
        sea_level_pressure
        temperature_and_dew_point
        visibility variable_wind vertical_visibility
        wind
      ).each do |key|
        attr = add_raw_if_present(attr, key)
      end
      %i(
        present_weather
        recent_weather remarks runway_visible_range
        sky_conditions
      ).each do |key|
        attr = add_raw_if_not_empty(attr, key)
      end
      attr[:cavok] = "CAVOK" if cavok?
      attr
    end

    private

    def add_raw_if_present(hash, attribute)
      value = send(attribute)
      return hash if value.nil?
      return hash if value.raw.nil?

      hash[attribute] = value.raw
      hash
    end

    def add_raw_if_not_empty(hash, attribute)
      values = send(attribute)
      raws = values.map(&:raw).compact
      return hash if raws.empty?

      hash[attribute] = raws.join(" ")
      hash
    end

    def analyze
      @chunks = @metar.split(' ')
      # Strip final '='
      if !strict?
        @chunks[-1].gsub!(/\s?=$/, '') if !@chunks.empty?
      end

      @station_code         = nil
      @time                 = nil
      @observer             = nil
      @wind                 = nil
      @variable_wind        = nil
      @cavok                = nil
      @visibility           = nil
      @minimum_visibility   = nil
      @runway_visible_range = []
      @present_weather      = []
      @sky_conditions       = []
      @vertical_visibility  = nil
      @temperature_and_dew_point = nil
      @sea_level_pressure   = nil
      @recent_weather       = []
      @unparsed             = []
      @remarks              = []

      seek_station_code
      seek_datetime
      seek_observer
      seek_wind
      seek_variable_wind
      seek_cavok
      if !cavok?
        seek_visibility
        seek_minimum_visibility
        seek_runway_visible_range
        seek_present_weather
        seek_sky_conditions
      end
      seek_vertical_visibility
      seek_temperature_dew_point
      seek_sea_level_pressure
      seek_recent_weather
      seek_to_remarks
      seek_remarks
    end

    def seek_station_code
      @station_code = Metar::Data::StationCode.parse(@chunks[0])
      if @station_code.nil?
        message = "Expecting location, found '#{@chunks[0]}' in #{@metar}"
        raise ParseError, message
      end
      @chunks.shift
      @station_code
    end

    def seek_datetime
      datetime = @chunks.shift
      @time = Metar::Data::Time.parse(
        datetime, year: raw.time.year, month: raw.time.month, strict: strict?
      )

      if !@time
        raise ParseError, "Expecting datetime, found '#{datetime}' in #{@metar}"
      end

      @time
    end

    def seek_observer
      @observer = Metar::Data::Observer.parse(@chunks[0])
      @chunks.shift if @observer.raw
      @observer
    end

    def seek_wind
      @wind = Metar::Data::Wind.parse(@chunks[0], strict: strict?)
      @chunks.shift if @wind
      @wind
    end

    def seek_variable_wind
      @variable_wind = Metar::Data::VariableWind.parse(@chunks[0])
      @chunks.shift if @variable_wind
      @variable_wind
    end

    def seek_cavok
      if @chunks[0] == 'CAVOK'
        @visibility = Metar::Data::Visibility.new(
          nil,
          distance: M9t::Distance.kilometers(10), comparator: :more_than
        )
        @present_weather << Metar::Data::WeatherPhenomenon.new(
          nil, phenomenon: "No significant weather"
        )
        @sky_conditions << Metar::Data::SkyCondition.new(nil) # = 'clear skies'
        @chunks.shift
        @cavok = true
      else
        @cavok = false
      end
    end

    # 15.10, 15.6.1
    def seek_visibility
      if observer.value == :auto # WMO 15.4
        if @chunks[0] == '////'
          @chunks.shift # Simply dispose of it
          return
        end
      end

      if @chunks[0] == '1' || @chunks[0] == '2'
        @visibility = Metar::Data::Visibility.parse(
          @chunks[0] + ' ' + @chunks[1]
        )
        if @visibility
          @chunks.shift
          @chunks.shift
        end
      else
        @visibility = Metar::Data::Visibility.parse(@chunks[0])
        @chunks.shift if @visibility
      end
      @visibility
    end

    # Optional after visibility: 15.6.2
    def seek_minimum_visibility
      @minimum_visibility = Metar::Data::Visibility.parse(@chunks[0])
      @chunks.shift if @minimum_visibility
      @minimum_visibility
    end

    def seek_runway_visible_range
      loop do
        rvr = Metar::Data::RunwayVisibleRange.parse(@chunks[0])
        break if rvr.nil?

        @chunks.shift
        @runway_visible_range << rvr
      end
      @runway_visible_range
    end

    def seek_present_weather
      if observer.value == :auto
        if @chunks[0] == '//' # WMO 15.4
          @present_weather << Metar::Data::WeatherPhenomenon.new(
            nil, phenomenon: "not observed"
          )
          @chunks.shift
          return
        end
      end

      if @chunks[0] == 'NSW'
        @present_weather << Metar::Data::WeatherPhenomenon.new(
          nil, phenomenon: "no significant weather"
        )
        @chunks.shift
        return
      end

      loop do
        break if @chunks.empty?
        break if @chunks[0].start_with?("RE")

        wtp = Metar::Data::WeatherPhenomenon.parse(@chunks[0])
        break if wtp.nil?

        @chunks.shift
        @present_weather << wtp
      end
    end

    # Repeatable: 15.9.1.3
    def seek_sky_conditions
      if observer.value == :auto # WMO 15.4
        if @chunks[0] == '///' || @chunks[0] == '//////'
          @chunks.shift # Simply dispose of it
          return
        end
      end

      loop do
        sky_condition = Metar::Data::SkyCondition.parse(@chunks[0])
        break if sky_condition.nil?

        @chunks.shift
        @sky_conditions << sky_condition
      end
    end

    def seek_vertical_visibility
      @vertical_visibility = Metar::Data::VerticalVisibility.parse(@chunks[0])
      @chunks.shift if vertical_visibility
      @vertical_visibility
    end

    def seek_temperature_dew_point
      @temperature_and_dew_point = Metar::Data::TemperatureAndDewPoint.parse(
        @chunks[0]
      )

      @chunks.shift if @temperature_and_dew_point
      @temperature_and_dew_point
    end

    def seek_sea_level_pressure
      @sea_level_pressure = Metar::Data::Pressure.parse(@chunks[0])
      @chunks.shift if @sea_level_pressure
      @sea_level_pressure
    end

    def seek_recent_weather
      loop do
        return if @chunks.empty?
        break if !@chunks[0].start_with?("RE")

        recent_weather = Metar::Data::WeatherPhenomenon.parse(@chunks[0])
        break if recent_weather.nil?

        @chunks.shift
        @recent_weather << recent_weather
      end
      @recent_weather
    end

    def seek_to_remarks
      if strict?
        if !@chunks.empty? && @chunks[0] != 'RMK'
          raise ParseError, "Unparsable text found: '#{@chunks.join(' ')}'"
        end
      else
        while !@chunks.empty? && @chunks[0] != 'RMK' do
          @unparsed << @chunks.shift
        end
      end
    end

    # WMO: 15.15
    def seek_remarks
      return if @chunks.empty?
      raise 'seek_remarks called without remark' if @chunks[0] != 'RMK'

      @chunks.shift # Drop 'RMK'
      @remarks = []
      loop do
        break if @chunks.empty?

        r = Metar::Data::Remark.parse(@chunks[0])
        if r
          if r.is_a?(Array)
            @remarks += r
          else
            @remarks << r
          end
          @chunks.shift
          next
        end
        if @chunks[0] == 'VIS' && @chunks.size >= 3 && @chunks[1] == 'MIN'
          @chunks.shift(2)
          r = Metar::Data::VisibilityRemark.parse(@chunks[0])
          @remarks << r
        end
        if @chunks[0] == 'DENSITY' && @chunks.size >= 3 && @chunks[1] == 'ALT'
          @chunks.shift(2)
          r = Metar::Data::DensityAltitude.parse(@chunks[0])
          @remarks << r
        end
        case
        when @chunks[0] =~ /^LTG(|CG|IC|CC|CA)$/
          r = Metar::Data::Lightning.parse_chunks(@chunks)
          @remarks << r
        else
          @remarks << @chunks.shift
        end
      end
    end

    def strict?
      self.class.compliance == :strict
    end
  end
end


text:
(C) Copyright 2014 William Dyce

All rights reserved. This program and the accompanying materials
are made available under the terms of the GNU Lesser General Public License
(LGPL) version 2.1 which accompanies this distribution, and is available at
http://www.gnu.org/licenses/lgpl-2.1.html

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
--]]

local Particle = {
	type = GameObject.newType("Particle")
}

local n_particles = 0

--[[------------------------------------------------------------
Fire
--]]--

local Fire = Class
{
  type = Particle.type,

  FRICTION = 6,

  init = function(self, x, y, dx, dy, dz, sizeMult)
    GameObject.init(self, x, y, 0)
    self.dx, self.dy, self.dz = dx, dy, dz or 0
    self.z = 0
    self.t = 0
    self.red = 200 + math.random()*55
    self.green = 200 + math.random()*25
    self.blue = 10 + math.random()*5
    self.dieSpeed = 1.3 + 1.2*math.random()
    self.sizeMult = (sizeMult or 1)
    size = self.sizeMult*8
    self.size = size*(1 + 0.5*math.random())

    n_particles = n_particles + 1
  end,
}
Fire:include(GameObject)

function Fire:update(dt)
	self.t = self.t + self.dieSpeed*dt*(1 + n_particles/75)
	self.r = math.max(0, math.sin(self.t*math.pi)*self.size)
	if self.t > 1 then
		self.purge = true
	end

	GameObject.update(self, dt)
	self.z = self.z + self.dz*dt
end

function Fire:draw(x, y)
	x, y = self.x, self.y
	love.graphics.setColor(self.red, self.green, self.blue)
		useful.oval("fill", x, y - self.z, self.r, self.r)
	useful.bindWhite()
	light(x, y, self.z, (1 - self.t)*self.sizeMult)
	light(x, y - self.z, 0, (1 - self.t)*self.sizeMult)
end

function Fire:onPurge()
	n_particles = n_particles - 1
end

Particle.Fire = Fire

--[[------------------------------------------------------------
Smoke
--]]--

local Smoke = Class
{
  type = Particle.type,

  FRICTION = 100,

  init = function(self, x, y, dx, dy, dz, size)
    GameObject.init(self, x, y, 0)
    self.dx, self.dy, self.dz = dx, dy, dz or 0
    self.z = 0
    self.t = 0
    self.a = 50 + math.random()*55
    size = (size or 1)*10
    self.size = size*(1 + 0.5)*math.random()
    self.dieSpeed = 0.5 + math.random()*0.7

    n_particles = n_particles + 1
  end,
}
Smoke:include(GameObject)

function Smoke:update(dt)
	self.t = self.t + self.dieSpeed*dt*(1 + n_particles/75)
	self.r = math.max(1, math.sin(self.t*math.pi)*self.size)
	if self.t > 1 then
		self.purge = true
	end

	GameObject.update(self, dt)
	self.z = self.z + self.dz*dt
end

function Smoke:draw(x, y)
	local r = self.r
	local shad_r = math.min(r, 32*r/self.z)

	useful.pushCanvas(SHADOW_CANVAS)
		useful.oval("fill", x, y, shad_r, shad_r*VIEW_OBLIQUE)
	useful.popCanvas()

	love.graphics.setColor(self.a, self.a, self.a)
		useful.oval("fill", x, y - self.z, r, r)
	useful.bindWhite()
end

function Smoke:onPurge()
	n_particles = n_particles - 1
end

Particle.Smoke = Smoke

--[[------------------------------------------------------------
Export
--]]--

return Particle


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace SEC\SolicitudesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * SEC\SolicitudesBundle\Entity\Persona
 *
 * @ORM\Table(name="tb_persona")
 * @ORM\Entity(repositoryClass="SEC\SolicitudesBundle\Entity\PersonaRepository")
 */

 class Persona {

     /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */

    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank()
     * @Assert\MaxLength(255)
     */

    protected $nombre;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank()
     * @Assert\MaxLength(255)
     */

    protected $apellido;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank()
     * @Assert\MaxLength(255)
     */

    protected $correo;

    /**
     * @ORM\OneToMany(targetEntity="Asignacion", mappedBy="persona")
     */
    Private $asignaciones;

}

?>


text:
#ifndef __GST_GL_WINDOW_WAYLAND_EGL_H__
#define __GST_GL_WINDOW_WAYLAND_EGL_H__

#include <wayland-client.h>
#include "xdg-shell-client-protocol.h"
#include <wayland-egl.h>
#include <wayland-cursor.h>

#include <gst/gl/gl.h>

G_BEGIN_DECLS

#define GST_TYPE_GL_WINDOW_WAYLAND_EGL         (gst_gl_window_wayland_egl_get_type())
#define GST_GL_WINDOW_WAYLAND_EGL(o)           (G_TYPE_CHECK_INSTANCE_CAST((o), GST_TYPE_GL_WINDOW_WAYLAND_EGL, GstGLWindowWaylandEGL))
#define GST_GL_WINDOW_WAYLAND_EGL_CLASS(k)     (G_TYPE_CHECK_CLASS((k), GST_TYPE_GL_WINDOW_WAYLAND_EGL, GstGLWindowWaylandEGLClass))
#define GST_IS_GL_WINDOW_WAYLAND_EGL(o)        (G_TYPE_CHECK_INSTANCE_TYPE((o), GST_TYPE_GL_WINDOW_WAYLAND_EGL))
#define GST_IS_GL_WINDOW_WAYLAND_EGL_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE((k), GST_TYPE_GL_WINDOW_WAYLAND_EGL))
#define GST_GL_WINDOW_WAYLAND_EGL_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS((o), GST_TYPE_GL_WINDOW_WAYLAND_EGL, GstGLWindowWaylandEGL_Class))

typedef struct _GstGLWindowWaylandEGL        GstGLWindowWaylandEGL;
typedef struct _GstGLWindowWaylandEGLClass   GstGLWindowWaylandEGLClass;

struct window;

struct display {
  struct wl_display      *display;
  struct wl_registry     *registry;
  struct wl_compositor   *compositor;
  struct wl_shell        *shell;
  struct wl_seat         *seat;
  struct wl_pointer      *pointer;
  struct wl_keyboard     *keyboard;
  struct wl_shm          *shm;
  struct wl_cursor_theme *cursor_theme;
  struct wl_cursor       *default_cursor;
  struct wl_surface      *cursor_surface;
  struct window          *window;
  guint32                 serial;

  gdouble pointer_x;
  gdouble pointer_y;
};

struct window {
  struct display *display;

  struct wl_event_queue     *queue;

  /* wl_shell */
  struct wl_surface         *surface;
  struct wl_shell_surface   *wl_shell_surface;
  /* XDG-shell */
  struct xdg_surface        *xdg_surface;
  struct xdg_toplevel       *xdg_toplevel;

  struct wl_egl_window      *native;
  struct wl_surface         *foreign_surface;
  struct wl_subsurface      *subsurface;
  struct wl_callback        *callback;
  int fullscreen, configured;
  int window_width, window_height;
  int preferred_width, preferred_height;
  int window_x, window_y;
  GstVideoRectangle render_rect;
};

struct _GstGLWindowWaylandEGL {
  /*< private >*/
  GstGLWindow parent;

  struct display display;
  struct window  window;

  GSource *wl_source;

  gpointer _reserved[GST_PADDING];
};

struct _GstGLWindowWaylandEGLClass {
  /*< private >*/
  GstGLWindowClass parent_class;

  /*< private >*/
  gpointer _reserved[GST_PADDING];
};

G_GNUC_INTERNAL
GType                   gst_gl_window_wayland_egl_get_type (void);

G_GNUC_INTERNAL
GstGLWindowWaylandEGL * gst_gl_window_wayland_egl_new  (GstGLDisplay * display);

G_GNUC_INTERNAL
void gst_gl_window_wayland_egl_create_window (GstGLWindowWaylandEGL * window_egl);

G_END_DECLS

#endif /* __GST_GL_WINDOW_WAYLAND_EGL_H__ */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.eclipse.emf.cdo.eresource.CDOResourceFolder (CDO Model Repository Documentation)</title>
<meta name="date" content="">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.eclipse.emf.cdo.eresource.CDOResourceFolder

Packages that use CDOResourceFolder

Package
Description

org.eclipse.emf.cdo.eresource

The generated EMF API of the CDO repository file system.

org.eclipse.emf.cdo.eresource.impl

The generated EMF implementation of the CDO repository file system.

org.eclipse.emf.cdo.eresource.util

The generated EMF utilities of the CDO repository file system.

org.eclipse.emf.cdo.transaction

Client concepts for dealing with transactions, distributed transactions and their save points.

org.eclipse.emf.cdo.ui

Reusable UI components specific to the CDO Model Repository.

org.eclipse.emf.cdo.util

Client utility classes, some common interfaces and exceptions.

org.eclipse.emf.cdo.view

Client concepts for dealing with views, view sets, queries, CDO objects and EMF resource sets.

org.eclipse.emf.spi.cdo

Client service provider interfaces and useful base implementations.

Uses of CDOResourceFolder in org.eclipse.emf.cdo.eresource

Methods in org.eclipse.emf.cdo.eresource that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
CDOResourceFolder.addResourceFolder(String name)

CDOResourceFolder
EresourceFactory.createCDOResourceFolder()

Returns a new object of class 'CDO Resource Folder'

CDOResourceFolder
CDOResourceNode.getFolder()

Returns the value of the 'Folder' container reference.

Methods in org.eclipse.emf.cdo.eresource with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

void
CDOResourceNode.setFolder(CDOResourceFolder value)

Sets the value of the 'Folder' container reference

Uses of CDOResourceFolder in org.eclipse.emf.cdo.eresource.impl

Classes in org.eclipse.emf.cdo.eresource.impl that implement CDOResourceFolder

Modifier and Type
Class and Description

class
CDOResourceFolderImpl

An implementation of the model object 'CDO Resource Folder'.

Methods in org.eclipse.emf.cdo.eresource.impl that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
CDOResourceFolderImpl.addResourceFolder(String name)

CDOResourceFolder
EresourceFactoryImpl.createCDOResourceFolder()

CDOResourceFolder
CDOResourceNodeImpl.getFolder()

Methods in org.eclipse.emf.cdo.eresource.impl with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

void
CDOResourceNodeImpl.basicSetFolder(CDOResourceFolder newFolder,
              boolean checkDuplicates)

void
CDOResourceImpl.setFolder(CDOResourceFolder newFolder)

void
CDOResourceNodeImpl.setFolder(CDOResourceFolder newFolder)

void
CDOResourceNodeImpl.setFolderGen(CDOResourceFolder newFolder)

Uses of CDOResourceFolder in org.eclipse.emf.cdo.eresource.util

Methods in org.eclipse.emf.cdo.eresource.util with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

T
EresourceSwitch.caseCDOResourceFolder(CDOResourceFolder object)

Returns the result of interpreting the object as an instance of 'CDO Resource Folder'

Uses of CDOResourceFolder in org.eclipse.emf.cdo.transaction

Methods in org.eclipse.emf.cdo.transaction that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
CDOPushTransaction.createResourceFolder(String path)

CDOResourceFolder
CDOTransaction.createResourceFolder(String path)

CDOResourceFolder
CDOPushTransaction.getOrCreateResourceFolder(String path)

CDOResourceFolder
CDOTransaction.getOrCreateResourceFolder(String path)

CDOResourceFolder
CDOPushTransaction.getResourceFolder(String path)

Methods in org.eclipse.emf.cdo.transaction with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

List<CDOResourceNode>
CDOPushTransaction.queryResources(CDOResourceFolder folder,
              String name,
              boolean exactMatch)

CloseableIterator<CDOResourceNode>
CDOPushTransaction.queryResourcesAsync(CDOResourceFolder folder,
                   String name,
                   boolean exactMatch)

Uses of CDOResourceFolder in org.eclipse.emf.cdo.ui

Methods in org.eclipse.emf.cdo.ui with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

void
CDOItemProvider.fillResourceFolder(IMenuManager manager,
                  CDOResourceFolder folder)

Uses of CDOResourceFolder in org.eclipse.emf.cdo.util

Methods in org.eclipse.emf.cdo.util that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
CDOBalancedTree.getRoot()

Constructors in org.eclipse.emf.cdo.util with parameters of type CDOResourceFolder

Constructor and Description

CDOBalancedTree(CDOResourceFolder root)

CDOBalancedTree(CDOResourceFolder root,
               int nodeCapacity)

CDOBalancedTree(CDOResourceFolder root,
               int folderCapacity,
               int resourceCapacity)

Uses of CDOResourceFolder in org.eclipse.emf.cdo.view

Methods in org.eclipse.emf.cdo.view that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
CDOView.getResourceFolder(String path)

Methods in org.eclipse.emf.cdo.view with parameters of type CDOResourceFolder

Modifier and Type
Method and Description

List<CDOResourceNode>
CDOView.queryResources(CDOResourceFolder folder,
              String name,
              boolean exactMatch)

Returns a list of the resources in the given folder with a name equal to or starting with the value of the name
 parameter.

CloseableIterator<CDOResourceNode>
CDOView.queryResourcesAsync(CDOResourceFolder folder,
                   String name,
                   boolean exactMatch)

Returns an iterator over the resources in the given folder with a name equal to or starting with the value of the
 name parameter.

Uses of CDOResourceFolder in org.eclipse.emf.spi.cdo

Methods in org.eclipse.emf.spi.cdo that return CDOResourceFolder

Modifier and Type
Method and Description

CDOResourceFolder
InternalCDOTransaction.getOrCreateResourceFolder(List<String> names)

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2011-2015 Eike Stepper (Berlin, Germany) and others.


text:
import argparse
import babel.dates
import datetime
import logging
import prettytable
import sys
import time

import zuul.rpcclient
import zuul.cmd

class Client(zuul.cmd.ZuulApp):
    log = logging.getLogger("zuul.Client")

    def parse_arguments(self):
        parser = argparse.ArgumentParser(
            description='Zuul Project Gating System Client.')
        parser.add_argument('-c', dest='config',
                            help='specify the config file')
        parser.add_argument('-v', dest='verbose', action='store_true',
                            help='verbose output')
        parser.add_argument('--version', dest='version', action='version',
                            version=self._get_version(),
                            help='show zuul version')

        subparsers = parser.add_subparsers(title='commands',
                                           description='valid commands',
                                           help='additional help')

        cmd_enqueue = subparsers.add_parser('enqueue', help='enqueue a change')
        cmd_enqueue.add_argument('--trigger', help='trigger name',
                                 required=True)
        cmd_enqueue.add_argument('--pipeline', help='pipeline name',
                                 required=True)
        cmd_enqueue.add_argument('--project', help='project name',
                                 required=True)
        cmd_enqueue.add_argument('--change', help='change id',
                                 required=True)
        cmd_enqueue.set_defaults(func=self.enqueue)

        cmd_enqueue = subparsers.add_parser('enqueue-ref',
                                            help='enqueue a ref')
        cmd_enqueue.add_argument('--trigger', help='trigger name',
                                 required=True)
        cmd_enqueue.add_argument('--pipeline', help='pipeline name',
                                 required=True)
        cmd_enqueue.add_argument('--project', help='project name',
                                 required=True)
        cmd_enqueue.add_argument('--ref', help='ref name',
                                 required=True)
        cmd_enqueue.add_argument(
            '--oldrev', help='old revision',
            default='0000000000000000000000000000000000000000')
        cmd_enqueue.add_argument(
            '--newrev', help='new revision',
            default='0000000000000000000000000000000000000000')
        cmd_enqueue.set_defaults(func=self.enqueue_ref)

        cmd_promote = subparsers.add_parser('promote',
                                            help='promote one or more changes')
        cmd_promote.add_argument('--pipeline', help='pipeline name',
                                 required=True)
        cmd_promote.add_argument('--changes', help='change ids',
                                 required=True, nargs='+')
        cmd_promote.set_defaults(func=self.promote)

        cmd_show = subparsers.add_parser('show',
                                         help='valid show subcommands')
        show_subparsers = cmd_show.add_subparsers(title='show')
        show_running_jobs = show_subparsers.add_parser(
            'running-jobs',
            help='show the running jobs'
        )
        show_running_jobs.add_argument(
            '--columns',
            help="comma separated list of columns to display (or 'ALL')",
            choices=self._show_running_jobs_columns().keys().append('ALL'),
            default='name, worker.name, start_time, result'
        )

        # TODO: add filters such as queue, project, changeid etc
        show_running_jobs.set_defaults(func=self.show_running_jobs)

        self.args = parser.parse_args()
        if self.args.func == self.enqueue_ref:
            if self.args.oldrev == self.args.newrev:
                parser.error("The old and new revisions must not be the same.")

    def setup_logging(self):
        """Client logging does not rely on conf file"""
        if self.args.verbose:
            logging.basicConfig(level=logging.DEBUG)

    def main(self):
        self.parse_arguments()
        self.read_config()
        self.setup_logging()

        self.server = self.config.get('gearman', 'server')
        if self.config.has_option('gearman', 'port'):
            self.port = self.config.get('gearman', 'port')
        else:
            self.port = 4730

        if self.args.func():
            sys.exit(0)
        else:
            sys.exit(1)

    def enqueue(self):
        client = zuul.rpcclient.RPCClient(self.server, self.port)
        r = client.enqueue(pipeline=self.args.pipeline,
                           project=self.args.project,
                           trigger=self.args.trigger,
                           change=self.args.change)
        return r

    def enqueue_ref(self):
        client = zuul.rpcclient.RPCClient(self.server, self.port)
        r = client.enqueue_ref(pipeline=self.args.pipeline,
                               project=self.args.project,
                               trigger=self.args.trigger,
                               ref=self.args.ref,
                               oldrev=self.args.oldrev,
                               newrev=self.args.newrev)
        return r

    def promote(self):
        client = zuul.rpcclient.RPCClient(self.server, self.port)
        r = client.promote(pipeline=self.args.pipeline,
                           change_ids=self.args.changes)
        return r

    def show_running_jobs(self):
        client = zuul.rpcclient.RPCClient(self.server, self.port)
        running_items = client.get_running_jobs()

        if len(running_items) == 0:
            print("No jobs currently running")
            return True

        all_fields = self._show_running_jobs_columns()
        if self.args.columns.upper() == 'ALL':
            fields = all_fields.keys()
        else:
            fields = [f.strip().lower() for f in self.args.columns.split(',')
                      if f.strip().lower() in all_fields.keys()]

        table = prettytable.PrettyTable(
            field_names=[all_fields[f]['title'] for f in fields])
        for item in running_items:
            for job in item['jobs']:
                values = []
                for f in fields:
                    v = job
                    for part in f.split('.'):
                        if hasattr(v, 'get'):
                            v = v.get(part, '')
                    if ('transform' in all_fields[f]
                        and callable(all_fields[f]['transform'])):
                        v = all_fields[f]['transform'](v)
                    if 'append' in all_fields[f]:
                        v += all_fields[f]['append']
                    values.append(v)
                table.add_row(values)
        print(table)
        return True

    def _epoch_to_relative_time(self, epoch):
        if epoch:
            delta = datetime.timedelta(seconds=(time.time() - int(epoch)))
            return babel.dates.format_timedelta(delta, locale='en_US')
        else:
            return "Unknown"

    def _boolean_to_yes_no(self, value):
        return 'Yes' if value else 'No'

    def _boolean_to_pass_fail(self, value):
        return 'Pass' if value else 'Fail'

    def _format_list(self, l):
        return ', '.join(l) if isinstance(l, list) else ''

    def _show_running_jobs_columns(self):
        """A helper function to get the list of available columns for
        `zuul show running-jobs`. Also describes how to convert particular
        values (for example epoch to time string)"""

        return {
            'name': {
                'title': 'Job Name',
            },
            'elapsed_time': {
                'title': 'Elapsed Time',
                'transform': self._epoch_to_relative_time
            },
            'remaining_time': {
                'title': 'Remaining Time',
                'transform': self._epoch_to_relative_time
            },
            'url': {
                'title': 'URL'
            },
            'result': {
                'title': 'Result'
            },
            'voting': {
                'title': 'Voting',
                'transform': self._boolean_to_yes_no
            },
            'uuid': {
                'title': 'UUID'
            },
            'launch_time': {
                'title': 'Launch Time',
                'transform': self._epoch_to_relative_time,
                'append': ' ago'
            },
            'start_time': {
                'title': 'Start Time',
                'transform': self._epoch_to_relative_time,
                'append': ' ago'
            },
            'end_time': {
                'title': 'End Time',
                'transform': self._epoch_to_relative_time,
                'append': ' ago'
            },
            'estimated_time': {
                'title': 'Estimated Time',
                'transform': self._epoch_to_relative_time,
                'append': ' to go'
            },
            'pipeline': {
                'title': 'Pipeline'
            },
            'canceled': {
                'title': 'Canceled',
                'transform': self._boolean_to_yes_no
            },
            'retry': {
                'title': 'Retry'
            },
            'number': {
                'title': 'Number'
            },
            'node_labels': {
                'title': 'Node Labels'
            },
            'node_name': {
                'title': 'Node Name'
            },
            'worker.name': {
                'title': 'Worker'
            },
            'worker.hostname': {
                'title': 'Worker Hostname'
            },
            'worker.ips': {
                'title': 'Worker IPs',
                'transform': self._format_list
            },
            'worker.fqdn': {
                'title': 'Worker Domain'
            },
            'worker.program': {
                'title': 'Worker Program'
            },
            'worker.version': {
                'title': 'Worker Version'
            },
            'worker.extra': {
                'title': 'Worker Extra'
            },
        }

def main():
    client = Client()
    client.main()

if __name__ == "__main__":
    sys.path.insert(0, '.')
    main()


text:
@interface SPMySQLConnection (Locking)

- (void)_lockConnection;
- (BOOL)_tryLockConnection;
- (void)_unlockConnection;

@end


text:
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.dao;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

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

import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.NewURIMaker;

public class NewURIMakerVitro implements NewURIMaker {
    private static final Log log = LogFactory.getLog(NewURIMakerVitro.class.getName());

    private static final int MAX_ATTEMPTS = 20;
    WebappDaoFactory wdf;
    Set<String> madeURIs = new HashSet<String>();
    static Random random = new Random();

    public NewURIMakerVitro( WebappDaoFactory wdf){
        this.wdf = wdf;
    }

    @Override
    public String getUnusedNewURI(String prefixURI) throws InsertException {

        Individual ind = new IndividualImpl();
        String newURI = null;
        int attempts = 0;
        boolean goodNewURI = false;
        log.debug("Before starting : Made URIs contains " + madeURIs.toString());

        while( ! goodNewURI && attempts < MAX_ATTEMPTS ){
            attempts++;

            if( attempts > 2 && prefixURI != null && !prefixURI.isEmpty() )
            {
            	log.debug("Attempts: " + attempts  + " and prefix not null and prefix not empty " + prefixURI);
                ind.setURI(prefixURI + random.nextInt() );
            }
            else {
            	log.debug("Attempts:" + attempts + " and setting uri to " + prefixURI);
                ind.setURI( prefixURI );
            }
            newURI = wdf.getIndividualDao().getUnusedURI( ind );
            log.debug("Created new uri " + newURI + " and does madeURIs contain it?" + madeURIs.contains(newURI));
            if( newURI != null && ! newURI.isEmpty() && ! madeURIs.contains( newURI) ){
            	log.debug("new URI is not null and new URI is empty and madeURIs does not containt new URI");
                goodNewURI = true;
                madeURIs.add( newURI );
            }
            log.debug("Made URIs contains " + madeURIs.toString());
        }
        if(goodNewURI && newURI != null && !newURI.isEmpty()) {
        	log.debug("Decided on this URI " + newURI);

            return newURI;
        }
        else {
            log.error("An error occurred and URI could not be created for prefix " + prefixURI);
        	throw new InsertException("Could not get a new URI for the prefix " + prefixURI );
        	}
    }

}


text:
const Repositories              = use('core/repositories');

const NotificationSmsRepository = Repositories.create('notification_sms', {});

module.exports = NotificationSmsRepository;


text:
FOUNDATION_EXPORT double OscarVersionNumber;

//! Project version string for Oscar.
FOUNDATION_EXPORT const unsigned char OscarVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Oscar/PublicHeader.h>


text:
import Reflux from 'reflux';
import StarProvider from '../utils/starProvider';

const StarActions = Reflux.createActions([
  'loadStars',
  'loadStarsSuccess',
  'loadStarsError'
]);

StarActions.loadStars.preEmit = function() {
  StarActions.loadStarsSuccess(StarProvider.getStars());
};

StarActions.toggleStar = function(isStarred, starInfo) {
  const stars = StarProvider.starChange(isStarred, starInfo);
  StarActions.loadStarsSuccess(stars);
};

export default StarActions;


text:
import * as config from '../../config';
import gulp from 'gulp';
import { join } from 'path';
import watch from 'gulp-watch';

gulp.task('watch', ['browser-sync'], () => {
  config.watch.watchableTasks.forEach((taskName) => {
    const task = config[taskName];
    if (!task) return;

    const source = join(config.SRC_DIR, task.src, task.glob);

    watch(source, () => gulp.start(taskName));
  });
});


text:
namespace chrono {
namespace vehicle {
namespace mrole {

/// @addtogroup vehicle_models_mrole
/// @{

/// Shafts-based 6-WD driveline for the mrole vehicle.
class CH_MODELS_API mrole_Driveline6WD : public ChShaftsDriveline6WD {
  public:
    mrole_Driveline6WD(const std::string& name);
    ~mrole_Driveline6WD() {}

    virtual double GetCentralDifferentialBoxInertia() const override { return m_central_differentialbox_inertia; }
    virtual double GetFrontDifferentialBoxInertia() const override { return m_front_differentialbox_inertia; }
    virtual double GetRearDifferentialBoxInertia() const override { return m_rear_differentialbox_inertia; }
    virtual double GetDriveshaftInertia() const override { return m_driveshaft_inertia; }
    virtual double GetToFrontDiffShaftInertia() const override { return m_frontshaft_inertia; }
    virtual double GetToRearDiffShaftInertia() const override { return m_rearshaft_inertia; }

    virtual double GetFrontConicalGearRatio() const override { return m_front_conicalgear_ratio; }
    virtual double GetRearConicalGearRatio() const override { return m_rear_conicalgear_ratio; }

    virtual double GetAxleDifferentialLockingLimit() const override { return m_axle_differential_locking_limit; }
    virtual double GetCentralDifferentialLockingLimit() const override { return m_central_differential_locking_limit; }

  private:
    // Shaft inertias.
    static const double m_central_differentialbox_inertia;
    static const double m_front_differentialbox_inertia;
    static const double m_rear_differentialbox_inertia;
    static const double m_driveshaft_inertia;
    static const double m_frontshaft_inertia;
    static const double m_rearshaft_inertia;

    // Gear ratios.
    static const double m_front_conicalgear_ratio;
    static const double m_rear_conicalgear_ratio;

    // Differential locking torque limits.
    static const double m_axle_differential_locking_limit;
    static const double m_central_differential_locking_limit;
};

/// @} vehicle_models_mrole

}  // namespace mrole
}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
package org.locationtech.geowave.datastore.hbase;

import java.io.IOException;
import org.locationtech.geowave.core.store.StoreFactoryHelper;
import org.locationtech.geowave.core.store.StoreFactoryOptions;
import org.locationtech.geowave.core.store.operations.DataStoreOperations;
import org.locationtech.geowave.datastore.hbase.config.HBaseRequiredOptions;
import org.locationtech.geowave.datastore.hbase.operations.HBaseOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HBaseFactoryHelper implements StoreFactoryHelper {
  private static final Logger LOGGER = LoggerFactory.getLogger(HBaseFactoryHelper.class);

  @Override
  public StoreFactoryOptions createOptionsInstance() {
    return new HBaseRequiredOptions();
  }

  @Override
  public DataStoreOperations createOperations(final StoreFactoryOptions options) {
    try {
      return HBaseOperations.createOperations((HBaseRequiredOptions) options);
    } catch (final IOException e) {
      LOGGER.error("Unable to create HBase operations from config options", e);
      return null;
    }
  }
}


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Spell_Advancement extends Spell
{
	public String ID() { return "Spell_Advancement"; }
	public String name(){ return "Advancement";}
	public String displayText(){ return "(Advancement)";}
	public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
	protected int canAffectCode(){return CAN_MOBS;}
	protected int canTargetCode(){return CAN_MOBS;}
	protected int overrideMana(){return 100;}
	public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT;}

	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		super.affectEnvStats(affected,affectableStats);
		affectableStats.setLevel(affectableStats.level() + 1);
	}

	public void affectCharStats(MOB affected, CharStats affectableStats)
	{
		super.affectCharStats(affected,affectableStats);
		CharClass C=affectableStats.getCurrentClass();
		affectableStats.setClassLevel(C,affectableStats.getClassLevel(C)+1);
	}

	public void unInvoke()
	{
		// undo the affects of this spell
		if((affected==null)||(!(affected instanceof MOB)))
			return;
		MOB mob=(MOB)affected;
		super.unInvoke();

		if(canBeUninvoked())
			mob.tell("Your temporary advancement has receded.");
	}

	public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
	{
		MOB target=this.getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			invoker=mob;

			CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":"^S<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>.^?");
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,"<S-NAME> become(s) more knowledgable!");
				beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			return beneficialWordsFizzle(mob,target,"<S-NAME> attempt(s) to invoke a spell, but fail(s) miserably.");

		// return whether it worked
		return success;
	}
}


text:
require 'formula'

class Rsnapshot < Formula
  homepage 'http://rsnapshot.org'
  url 'http://rsnapshot.org/downloads/rsnapshot-1.3.1.tar.gz'
  sha1 'a3aa3560dc389e1b00155a5869558522c4a29e05'

  head 'cvs://:pserver:anonymous:@rsnapshot.cvs.sourceforge.net:/cvsroot/rsnapshot:rsnapshot'

  def install
    system "./configure", "--disable-debug", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--mandir=#{man}"
    system "make install"
  end
end


text:
#include "config.h"

#include "client.h"
#include "user.h"
#include "vnc.h"

#ifdef ENABLE_COMMON_SSH
#include "common-ssh/sftp.h"
#include "common-ssh/ssh.h"
#include "common-ssh/user.h"
#endif

#ifdef ENABLE_PULSE
#include "pulse/pulse.h"
#endif

#include <guacamole/client.h>
#include <guacamole/recording.h>

#include <pthread.h>
#include <stdlib.h>
#include <string.h>

int guac_client_init(guac_client* client) {

    /* Set client args */
    client->args = GUAC_VNC_CLIENT_ARGS;

    /* Alloc client data */
    guac_vnc_client* vnc_client = calloc(1, sizeof(guac_vnc_client));
    client->data = vnc_client;

#ifdef ENABLE_VNC_TLS_LOCKING
    /* Initialize the TLS write lock */
    pthread_mutex_init(&vnc_client->tls_lock, NULL);
#endif

    /* Init clipboard */
    vnc_client->clipboard = guac_common_clipboard_alloc();

    /* Set handlers */
    client->join_handler = guac_vnc_user_join_handler;
    client->leave_handler = guac_vnc_user_leave_handler;
    client->free_handler = guac_vnc_client_free_handler;

    return 0;
}

int guac_vnc_client_free_handler(guac_client* client) {

    guac_vnc_client* vnc_client = (guac_vnc_client*) client->data;
    guac_vnc_settings* settings = vnc_client->settings;

    /* Clean up VNC client*/
    rfbClient* rfb_client = vnc_client->rfb_client;
    if (rfb_client != NULL) {

        /* Wait for client thread to finish */
        pthread_join(vnc_client->client_thread, NULL);

        /* Free memory that may not be free'd by libvncclient's
         * rfbClientCleanup() prior to libvncclient 0.9.12 */

        if (rfb_client->frameBuffer != NULL) {
            free(rfb_client->frameBuffer);
            rfb_client->frameBuffer = NULL;
        }

        if (rfb_client->raw_buffer != NULL) {
            free(rfb_client->raw_buffer);
            rfb_client->raw_buffer = NULL;
        }

        if (rfb_client->rcSource != NULL) {
            free(rfb_client->rcSource);
            rfb_client->rcSource = NULL;
        }

        /* Free VNC rfbClientData linked list (may not be free'd by
         * rfbClientCleanup(), depending on libvncclient version) */

        while (rfb_client->clientData != NULL) {
            rfbClientData* next = rfb_client->clientData->next;
            free(rfb_client->clientData);
            rfb_client->clientData = next;
        }

        rfbClientCleanup(rfb_client);

    }

#ifdef ENABLE_COMMON_SSH
    /* Free SFTP filesystem, if loaded */
    if (vnc_client->sftp_filesystem)
        guac_common_ssh_destroy_sftp_filesystem(vnc_client->sftp_filesystem);

    /* Free SFTP session */
    if (vnc_client->sftp_session)
        guac_common_ssh_destroy_session(vnc_client->sftp_session);

    /* Free SFTP user */
    if (vnc_client->sftp_user)
        guac_common_ssh_destroy_user(vnc_client->sftp_user);

    guac_common_ssh_uninit();
#endif

    /* Clean up recording, if in progress */
    if (vnc_client->recording != NULL)
        guac_recording_free(vnc_client->recording);

    /* Free clipboard */
    if (vnc_client->clipboard != NULL)
        guac_common_clipboard_free(vnc_client->clipboard);

    /* Free display */
    if (vnc_client->display != NULL)
        guac_common_display_free(vnc_client->display);

#ifdef ENABLE_PULSE
    /* If audio enabled, stop streaming */
    if (vnc_client->audio)
        guac_pa_stream_free(vnc_client->audio);
#endif

    /* Free parsed settings */
    if (settings != NULL)
        guac_vnc_settings_free(settings);

#ifdef ENABLE_VNC_TLS_LOCKING
    /* Clean up TLS lock mutex. */
    pthread_mutex_destroy(&(vnc_client->tls_lock));
#endif

    /* Free generic data struct */
    free(client->data);

    return 0;
}


text:
layout: default
---

                    Improve this page

{% if page.chapter %}{{ page.chapter }} - {% endif %}{{ page.title }}

                  {{ content }}

            {% include docs_contents.html %}


text:
<script src="//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
<script src="//cdn.bootcss.com/highlight.js/9.12.0/languages/r.min.js"></script>

<script>
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
</script>


text:
module PortalSender

  class Protocol
    VersionRoutePrefix = "protocol_version"
    Versions =[
        { name: "1", serialization_method_name: :response_for_portal_1_0 },
        { name: "0", serialization_method_name: :response_for_portal     }
    ]

    PortalProtocolMap = {}

    def self.instance(endpoint)
      uri = URI.parse(endpoint)
      portal_key   = "#{uri.host}:#{uri.port}"
      PortalProtocolMap[portal_key] ||= self.new
      PortalProtocolMap[portal_key]
    end

    def initialize()
      @last_try      = 12.months.ago
      @version_index = 0
    end

    def version
      Versions[@version_index]
    end

    def retry_interval
      20.minutes
    end

    def assume_latest_version
      @version_index = 0
    end

    def versioned_endpoint(endpoint)
      # special case the oldest portals that didn't have an versioned endpoint
      if @version_index == oldest_version_index
        return endpoint
      end
      "#{endpoint}/#{PortalSender::Protocol::VersionRoutePrefix}/#{self.version[:name]}"
    end

    def post_answers(answers, remote_endpoint, start_time = nil)
      assume_latest_version if @last_try < retry_interval.ago
      try_again = true
      while try_again
        @last_try = Time.now
        serialized_data = self.send serialization_method_name, answers, start_time
        response = HTTParty.post(
            versioned_endpoint(remote_endpoint), {
            :body => serialized_data,
            :headers => {
                "Authorization" => Concord::AuthPortal.auth_token_for_url(remote_endpoint),
                "Content-Type" => 'application/json'
            }
        })
        return true if response.success?
        Rails.logger.error "URL: #{versioned_endpoint(remote_endpoint)} |#{response.code}| #{response.message}"
        try_again = can_try_earlier_version?
        next_version!
      end
      return false
    end

    def oldest_version_index
      return Versions.length() -1
    end

    def can_try_earlier_version?
      @version_index < oldest_version_index
    end

    def next_version!
      if can_try_earlier_version?
        @version_index = @version_index + 1
      end
    end

    def serialization_method_name
      version[:serialization_method_name]
    end

    def arrayify_answers(answer)
      if answer.kind_of? Array
        answer
      else
        [answer]
      end
    end

    ################################################
    # Version 1.0 of the protocol
    ################################################
    def response_for_portal_1_0(_answer, start_time = nil)
      answers  = arrayify_answers(_answer)

      data_for_portal = {
        answers: answers.map { |ans| ans.portal_hash },
        version: "1",
        lara_end: Time.now.utc.to_s,
      }

      # lara_start is used by the portal to track how long the latency is from a change
      # made by a student in LARA to when that changes is fully available in the portal.
      if start_time
        data_for_portal[:lara_start] = start_time.utc.to_s
      end

      return data_for_portal.to_json
    end

    ################################################
    # Version 0.0 of the protocol
    ################################################
    def response_for_portal(_answer, start_time = nil)
      answers = arrayify_answers(_answer)
      answers.map { |ans| ans.portal_hash }.to_json
    end

  end

end


text:
package lexek.httpserver;

import lexek.wschat.chat.model.GlobalRole;
import lexek.wschat.db.model.UserDto;

import javax.ws.rs.core.SecurityContext;
import java.security.Principal;

public class JerseySecurityContext implements SecurityContext {
    private final UserDto userDto;

    public JerseySecurityContext(UserDto userDto) {
        this.userDto = userDto;
    }

    @Override
    public Principal getUserPrincipal() {
        return userDto;
    }

    @Override
    public boolean isUserInRole(String role) {
        return userDto.hasRole(GlobalRole.valueOf(role));
    }

    @Override
    public boolean isSecure() {
        return true;
    }

    @Override
    public String getAuthenticationScheme() {
        return "SID";
    }
}


text:
package org.alienideology.jcord.internal.object;

import org.json.JSONObject;

/**
 * Jsonable - Objects that can be serialized to json.
 * @author AlienIdeology
 */
@FunctionalInterface
public interface Jsonable {

    /**
     * Build an json object, used for building an object and sent it to Discord Gateway.
     *
     * @return The json object built.
     */
    JSONObject toJson();

}