text:
<file_sep>//window.onload = function() {
//
//	var searchButton = document.getElementById("searchButton");
//	var searchForm = document.getElementById("searchForm");
//	searchButton.onclick = onSearchButton;
//
//	function onSearchButton() {
//		searchForm.style.display = "block";
//		searchButton.style.display = "none";
//	}
//
//	var searchFormButton = document.getElementById("searchFormButton");
//	searchFormButton.onclick = onSearchFormButton;
//
//	function onSearchFormButton() {
//		if(document.getElementById("selectName").value == "") {
//			searchForm.style.display = "none";
//			searchButton.style.display = "block";
//		}
//	}
//}
window.onload = function() {
	var images = document.getElementById("images");
	images.onclick = imagesOn;
	function imagesOn() {
		window.location.href = "management";
	}
}<file_sep>CREATE SCHEMA dragon;

#借书记录表，id为自动生成，student_id为学号，booknumber为书的编号
CREATE TABLE dragon.borrowrecord (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` varchar(11) NOT NULL,
  `booknumber` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

#评论纪录表，id为自动生成，student_id为学号，discuss为评价，booknumber为书的编号
CREATE TABLE dragon.discuss (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `discuss` varchar(200) NOT NULL,
  `booknumber` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

#管理表，booknumber为书的编号为自动生成，name为书的名称，summary为书的简介，quantity为书的库存量，author为作者名称，bookimages为书本的图片名
CREATE TABLE dragon.management (
  `booknumber` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`summary` varchar(200) NOT NULL,
`quantity` int(11) NOT NULL,
`author` varchar(45) NOT NULL,
`bookimages` varchar(45) NOT NULL,
`type` varchar(45) NOT NULL,
PRIMARY KEY (`booknumber`)
);

#登录注册表
CREATE TABLE dragon.loginregist (
  `number` int(11) NOT NULL AUTO_INCREMENT,

  `student_id` int(11) NOT NULL,
  `student_name` varchar(45) DEFAULT NULL,

`password` varchar(45) NOT NULL,
  `sex` varchar(45) DEFAULT NULL,

 `email` varchar(45) DEFAULT NULL,
  `home` varchar(45) DEFAULT NULL,

`sign` varchar(100) DEFAULT NULL,

 PRIMARY KEY (`number`),
  UNIQUE KEY `student_id_UNIQUE` (`student_id`)
);
 ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

<file_sep>			html,body { height: 100%; background-color:#eee ;}
			.page-header{position: relative;}
			.page-header > .del{ position: absolute;right: 0;top: 0;}
			.page-header > .loginregister{ position: absolute;right: 150px;top: 0;}
			.container-fluid { min-height: 100%; background-image: url(../img/background-image/book-background-image2.jpg);
			background-repeat: no-repeat;background-size: cover;}
			.container-fluid>.contant { height: 100%; color: #fff;}
			.container-fluid >.contant > .centrality >.recommend >img{padding: 2% 0;}
			.navbar{border: 0;}
			.navbar-default .navbar-brand,.navbar-default .navbar-nav>li>a,.dropdown-menu>li>a{color: #fff;}
			.navbar-default{background-color: transparent;}
			.container-fluid > .contant > .top > .navbar > .collapse > .nav > .dropdown > .dropdown-toggle ,
			.container-fluid > .contant > .top > .navbar > .collapse > .nav > .dropdown > .dropdown-menu,
			.dropdown-menu>li>a:hover { background-color: transparent;}
<file_sep>package com.gupt.dragon.impl.service;

import com.gupt.dragon.dao.StudentDao;
import com.gupt.dragon.service.StudentService;

public class StudentServiceImpl implements StudentService{
	private StudentDao studentDao;

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

	@Override
	public String selectStudent() {
		return studentDao.selectStudent();
	}

}
<file_sep>package com.dragon.common;

public class Management {
  private int number;
  private String name;
  private String summary;
  private int quantity;
  private String author;
  private String images;
  private String type;

  public int getNumber() {
    return number;
  }
  public void setNumber(int number) {
    this.number = number;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public int getQuantity() {
    return quantity;
  }
  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }
  public String getAuthor() {
    return author;
  }
  public void setAuthor(String author) {
    this.author = author;
  }
  public String getImages() {
    return images;
  }
  public void setImages(String images) {
    this.images = images;
  }

  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }

  @Override
  public String toString() {
    return "Management [number=" + number + ", name=" + name + ", summary="
        + summary + ", quantity=" + quantity + ", author=" + author
        + ", images=" + images + ", type=" + type + "]";
  }
}
<file_sep>package com.dragon.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.dragon.common.LoginRegister;

public final class LoginRegisterDao {

	public Connection connection;

	public LoginRegisterDao(Connection connection) {
		this.connection = connection;
	}

	public boolean createLoginRegist(int studentId, String password) throws SQLException {
		int result;
		String sql = "insert into loginregist(student_id,password) values (?,?)";
		PreparedStatement statement = null;
		try {
			statement = connection.prepareStatement(sql);
			statement.setInt(1, studentId);
			statement.setString(2, password);
			result = statement.executeUpdate();

		} finally {
			// 关闭statement，以释放占用的资源。
			if (statement != null) {
				statement.close();
			}
		}
		return result != 0;
	}

	public boolean retrieveLoginRegistName(int studentId) throws SQLException {

		boolean result = false;
		String sql = "select student_id from loginregist where student_id = ?";
		PreparedStatement statement = null;

		try {
			statement = connection.prepareStatement(sql);
			statement.setInt(1, studentId);
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				result = true;
			}
		} finally {
			// 关闭statement，以释放占用的资源。
			if (statement != null) {
				statement.close();
			}
		}
		return result;
	}

	public LoginRegister retrieveLoginRegistNameAndPassword(int studentId) throws SQLException {

		LoginRegister result = new LoginRegister();
		String sql = "select student_id,password from loginregist where student_id = ?";
		PreparedStatement statement = null;

		try {
			statement = connection.prepareStatement(sql);
			statement.setInt(1, studentId);
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				result.setStudentId(resultSet.getInt(1));
				result.setPassword(resultSet.getString(2));
			}
		} finally {
			// 关闭statement，以释放占用的资源。
			if (statement != null) {
				statement.close();
			}
		}
		return result;
	}

	public LoginRegister retrieveLoginRegistAllByStudentId(int studentId) throws SQLException {

		LoginRegister result = new LoginRegister();
		String sql = "select student_id,password,student_name,sex,email,home,sign from loginregist where student_id = ?";
		PreparedStatement statement = null;

		try {
			statement = connection.prepareStatement(sql);
			statement.setInt(1, studentId);
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				result.setStudentId(resultSet.getInt(1));
				result.setPassword(resultSet.getString(2));
				result.setStudentName(resultSet.getString(3));
				result.setSex(resultSet.getString(4));
				result.setEmail(resultSet.getString(5));
				result.setHone(resultSet.getString(6));
				result.setSign(resultSet.getString(7));
			}
		} finally {
			// 关闭statement，以释放占用的资源。
			if (statement != null) {
				statement.close();
			}
		}
		return result;
//		update loginregist set student_name = 'dragon',sex = '男',email = '<EMAIL>',home = '广东',sign = 'is打死U盾有氨甲环酸都看见俺是短上衣 阿达牛啊丢阿姨带收到货啊啊丢啊啊' where student_id = 123
	}

	public int updateLoginRegistByStudentId(LoginRegister loginRegist) throws SQLException {
		int result = 0;
		String sql = "update loginregist set student_name = ?,sex = ?,email = ?,home = ?,sign =? where student_id = ?";
		PreparedStatement statement = null;
		try {
			statement = connection.prepareStatement(sql);
			int i = 1;
			statement.setString(i++, loginRegist.getStudentName());
			statement.setString(i++, loginRegist.getSex());
			statement.setString(i++, loginRegist.getEmail());
			statement.setString(i++, loginRegist.getHone());
			statement.setString(i++, loginRegist.getSign());
			statement.setInt(i++, loginRegist.getStudentId());
			result = statement.executeUpdate();
		} finally {
			// 关闭statement，以释放占用的资源。
			if (statement != null) {
				statement.close();
			}
		}
		return result;
	}

}
<file_sep>window.onload = function() {
	if(document.getElementById("success").innerHTML == "借书成功") {
		document.getElementById("nav-profile").classList.add("active");
		document.getElementById("nav-home").classList.remove("active");
		document.getElementById("profile").classList.add("active");
		document.getElementById("home").classList.remove("active");
	}
}<file_sep>package com.dragon.common;

public class Discuss {

  private int studentId;
  private String discuss;
  private int booknumber;

  public int getStudentId() {
    return studentId;
  }
  public void setStudentId(int studentId) {
    this.studentId = studentId;
  }
  public String getDiscuss() {
    return discuss;
  }
  public void setDiscuss(String discuss) {
    this.discuss = discuss;
  }
  public int getBooknumber() {
    return booknumber;
  }
  public void setBooknumber(int booknumber) {
    this.booknumber = booknumber;
  }
  @Override
  public String toString() {
    return "Discuss [studentId=" + studentId + ", discuss=" + discuss
        + ", booknumber=" + booknumber + "]";
  }
}
<file_sep><%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page
	import="java.util.List,com.dragon.common.StringConstant,com.dragon.common.Management,com.dragon.common.LoginRegister"%>
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="img/LOGO16mm.png">
<link rel="stylesheet" type="text/css"
	href="bootstrap/css/bootstrap.min.css" />

<link rel="stylesheet" type="text/css"
	href="font-awesome-4.7.0/css/font-awesome.css" />
<link rel="stylesheet" type="text/css" href="css/user.css" />

<title></title>

				UPCOMING 图书管理系统

				登录

				<%=session.getAttribute(StringConstant.SESSION_STUDENTID)%>
				退出登录

								USER

								已借书籍

								已还书籍

											<%
												LoginRegister loginRegister = (LoginRegister) request.getAttribute(StringConstant.REQ_LOGINREGISTER);
											%>

														USER

头像

学号

<%=loginRegister.getStudentId()%>

昵称

<%=loginRegister.getStudentName()%>

签名

<%=loginRegister.getSign()%>

性别

<%=loginRegister.getSex()%>

家乡

<%=loginRegister.getHone()%>

邮箱

<%=loginRegister.getEmail()%>

										编辑

											USER

										<form class="form-horizontal" action="LoginRegister"
											method="post">
											<input type="text" name="studentId" style="display: none"
												value="<%=loginRegister.getStudentId()%>">

												 昵称

													<input type="text" class="form-control" id="name"
														name="name" placeholder="昵称"
														value="<%=loginRegister.getStudentName()%>">

												签名

													<textarea class="form-control" rows="3" id="autograph"
														name="autograph" placeholder="签名"
														value="<%=loginRegister.getSign()%>"></textarea>

												性别

													 <input type="radio" name="optionsRadios"
														id="optionsRadios1" value="男" checked>男
													  <input type="radio" name="optionsRadios"
														id="optionsRadios2" value="女"> 女

													家乡

													<input type="text" class="form-control" id="hometown"
														name="hometown" placeholder="家乡"
														value="<%=loginRegister.getHone()%>">

													email

													<input type="email" class="form-control" id="email"
														name="email" placeholder="email"
														value="<%=loginRegister.getEmail()%>">

											<button class="btn btn-primary col-md-offset-3 col-md-3">完成</button>
										</form>

								已借书籍

								<%
									int result = (int) request.getAttribute(StringConstant.REQ_UPDATEBORROW);

									if (result == 1) {
								%>

预借书成功

								<%
									}
									List<Management> managementList = (List) request.getAttribute(StringConstant.REQ_RECORD);
									for (int i = 0; i < managementList.size(); i++) {
										Management management = managementList.get(i);
								%>

										<img class="col-md-offset-1 col-md-10"
											src="/MyDragonBookimages/<%=management.getImages()%>">

<%=management.getName()%>

								<%
									}
								%>

								已还书籍

<file_sep>package com.dragon.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dragon.common.LoginRegister;
import com.dragon.common.Management;
import com.dragon.common.StringConstant;
import com.dragon.service.BorrowRecordService;
import com.dragon.service.LoginRegisterService;
import com.dragon.service.ManagementService;

/**
 * Servlet implementation class BorrowRecordServlet
 */
@WebServlet("/borrowrecord")
public final class BorrowRecordServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public BorrowRecordServlet() {
    super();
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();

    int studentId = (int) session
        .getAttribute(StringConstant.SESSION_STUDENTID);

    //获取用户信息
    LoginRegisterService LoginRegisterService = new LoginRegisterService();
    LoginRegister loginRegister = LoginRegisterService.retrieveLoginRegistAllByStudentId(studentId);
    request.setAttribute(StringConstant.REQ_LOGINREGISTER, loginRegister);

    String booknumber = request.getParameter("booknumber");

    booknumber = booknumber != null ? booknumber : "0";

    BorrowRecordService borrowRecordService = new BorrowRecordService();

    ManagementService managementService = new ManagementService();

    request.setAttribute(StringConstant.REQ_UPDATEBORROW, 0);

    if (!booknumber.equals("0")) {
      int result = borrowRecordService.createBorrow(studentId,
          Integer.parseInt(booknumber));

      request.setAttribute(StringConstant.REQ_UPDATEBORROW, result);
    }

    List<Integer> recordList = borrowRecordService
        .retrieveBooknumberByStudentId(studentId);

    List<Management> managementList = new ArrayList<Management>();

    for (int i = 0; i < recordList.size(); i++) {

      Management management = new Management();

      management = managementService
          .retrieveManagementAllNameAndImagesByBooknumber(recordList.get(i));

      managementList.add(management);
    }

    request.setAttribute(StringConstant.REQ_RECORD, managementList);

    // 设置转发页面为user.jsp
    RequestDispatcher dispatcher = request
        .getRequestDispatcher("user.jsp");
    // 转发
    dispatcher.forward(request, response);

  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
	      throws ServletException, IOException {
	  doGet(request, response);
  }

}
<file_sep>package com.dragon.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dragon.common.LoginRegister;
import com.dragon.common.StringConstant;
import com.dragon.service.LoginRegisterService;

/**
 * Servlet implementation class LoginRegisterServlet
 */
@WebServlet("/LoginRegister")
public class LoginRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginRegisterServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); // 设置请求数据的解码字符集

		HttpSession session = request.getSession();

		String loginRegist = request.getParameter("loginRegist");

		int studentId = Integer.parseInt(request.getParameter("input-login-register"));

		String password = request.getParameter("inputPassword");

		LoginRegisterService loginRegisterService = LoginRegisterService.INSTANCE;

		RequestDispatcher dispatcher = request.getRequestDispatcher("LoginRegist.html");

		if(loginRegist.equals("login")) {
			LoginRegister loginRegistNameAndPassword = loginRegisterService.
					retrieveLoginRegistNameAndPassword(studentId);
			if(studentId == loginRegistNameAndPassword.getStudentId() && password.equals(loginRegistNameAndPassword.getPassword())) {
				dispatcher = request.getRequestDispatcher("index.html");
			    session.setAttribute(StringConstant.SESSION_STUDENTID, studentId);
			}
		}else if(loginRegist.equals("register")) {
			loginRegisterService.createLoginRegist(studentId, password);
		}
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int studentId = Integer.parseInt(request.getParameter("studentId"));
		String studentName = request.getParameter("name");
		String sign = request.getParameter("autograph");
		String sex = request.getParameter("optionsRadios");
		String hone = request.getParameter("hometown");
		String email = request.getParameter("email");
		LoginRegister loginRegister = new LoginRegister();
		loginRegister.setEmail(email);
		loginRegister.setHone(hone);
		loginRegister.setSex(sex);
		loginRegister.setSign(sign);
		loginRegister.setStudentId(studentId);
		loginRegister.setStudentName(studentName);
		LoginRegisterService loginRegisterService = new LoginRegisterService();
		loginRegisterService.updateLoginRegistByStudentId(loginRegister);
		RequestDispatcher dispatcher = request.getRequestDispatcher("borrowrecord");
		dispatcher.forward(request, response);
	}
}
<file_sep>package com.gupt.dragon.service;

public interface StudentService {
	String selectStudent();
}
<file_sep>window.onload = function() {
	var aLoginSubmit = document.getElementById("a-loginSubmit");
	aLoginSubmit.onclick = doFormLoginSubnit;

	function doFormLoginSubnit() {
		if(document.getElementById("input-login").value != "" &&
			document.getElementById("inputPassword").value != "") {
			document.getElementById("formS").submit();
		}
	}
}<file_sep>package com.dragon.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.dragon.common.Discuss;

public class DiscussDao {

  public Connection connection;

  public DiscussDao(Connection connection) {
    this.connection = connection;
  }

  public int createDiscuss(Discuss discuss) throws SQLException {
    int result = 0;
    String sql = "insert into discuss (student_id,discuss,booknumber) values (?,?,?)";
    PreparedStatement statement = null;
    try {
      statement = connection.prepareStatement(sql);
      statement.setInt(1, discuss.getStudentId());
      statement.setString(2,discuss.getDiscuss());
      statement.setInt(3,discuss.getBooknumber());

      result = statement.executeUpdate();

    }finally{
   // 关闭statement，以释放占用的资源。
      if (statement != null) {
        statement.close();
      }
    }
    return result;
  }

  public List<Discuss> retrieveDiscussAll() throws SQLException {
    List<Discuss> discussList = null;

    String sql = "select student_id,discuss,booknumber from discuss";

    Statement statement = null;

    try {
      discussList = new ArrayList<Discuss>();
      statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(sql);
      while(resultSet.next()) {
        Discuss discuss = new Discuss();
        discuss.setStudentId(resultSet.getInt(1));
        discuss.setDiscuss(resultSet.getString(2));
        discuss.setBooknumber(resultSet.getInt(3));
        discussList.add(discuss);
      }
    }finally {
      // 关闭statement，以释放占用的资源。
      if (statement != null) {
        statement.close();
      }
    }
    return discussList;
  }
  public List<Discuss> retrieveDiscussByBooknumber(int booknumber) throws SQLException {
	    List<Discuss> discussList = null;

	    String sql = "select student_id,discuss from discuss where booknumber = ?";

	    PreparedStatement statement = null;

	    try {
	      discussList = new ArrayList<Discuss>();
	      statement = connection.prepareStatement(sql);
	      statement.setInt(1, booknumber);

	      ResultSet resultSet = statement.executeQuery();
	      while(resultSet.next()) {
	        Discuss discuss = new Discuss();
	        discuss.setStudentId(resultSet.getInt(1));
	        discuss.setDiscuss(resultSet.getString(2));
	        discussList.add(discuss);
	      }
	    }finally {
	      // 关闭statement，以释放占用的资源。
	      if (statement != null) {
	        statement.close();
	      }
	    }
	    return discussList;
	  }

  public boolean retrieveStudentIdByBooknumber(int booknumber,int studentId) throws SQLException {
    boolean result = false;
    String sql = "select student_id from discuss where booknumber = ?";
    PreparedStatement statement = null;
    try {
      statement = connection.prepareStatement(sql);
      statement.setInt(1, booknumber);
      ResultSet rs = statement.executeQuery();
      while(rs.next()) {
    	  String ts = rs.getString(1);
         if(ts.equals(studentId) ) {
        	 result = true;
         }

      }
    }finally {
      // 关闭statement，以释放占用的资源。
      if (statement != null) {
        statement.close();
      }
    }
    return result;
  }

}
<file_sep>package com.dragon.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.dragon.access.AccessHelper;
import com.dragon.dao.BorrowDao;
import com.dragon.dao.ManagementDao;

public class BorrowRecordService {

  public static final BorrowRecordService INSTANCE = new BorrowRecordService(); // 创建单例

  private AccessHelper accessHelper = AccessHelper.INSTANCE; // 资源访问助手

  public BorrowRecordService() {

  }

  public int createBorrow(int studentId ,int booknumber) {
    int result = 0;

    // 创建数据库连接，并关闭自动提交（autoCommit）。
    Connection connection = accessHelper.createConnection(false);

    BorrowDao borrowDao = new BorrowDao(connection);
    ManagementDao managementDao = new ManagementDao(connection);
    try {
      int update = managementDao.updateManagementByBooknumber(booknumber);
      if(update == 1) {
        result = borrowDao.createBorrow(studentId, booknumber);
      }

      connection.commit();
    } catch (SQLException e) {
      // 若抛出异常，需回滚事务，最好如下显式地回滚。
      rollback(connection);
      // 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
      throw new RuntimeException(e);
    } finally {
      // 关闭连接，以释放占用的资源。
      close(connection);
    }
    return result;
  }

  public List<Integer> retrieveBooknumberByStudentId(int studentId) {
    List<Integer> recordList= new ArrayList<Integer>();

    Connection connection = accessHelper.createConnection(false);

    BorrowDao borrowDao = new BorrowDao(connection);

    try {
      recordList = borrowDao.retrieveBooknumberByStudentId(studentId);

    } catch (SQLException e) {
      // 若抛出异常，需回滚事务，最好如下显式地回滚。
      rollback(connection);
      // 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
      throw new RuntimeException(e);
    } finally {
      // 关闭连接，以释放占用的资源。
      close(connection);
    }
    return recordList;
  }

  private void rollback(Connection connection) {
    try {
      connection.rollback();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  private void close(Connection connection) {
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
  }

}
<file_sep>package com.gupt.dragon.impl.dao;

import com.gupt.dragon.dao.StudentDao;

public class StudentDaoImpl implements StudentDao{

	@Override
	public String selectStudent() {
		return "zs";
	}

}
<file_sep>package com.gupt.dragon.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gupt.dragon.common.Student;

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student student = (Student)context.getBean("student");
		System.out.println(student.getClass());
	}
}
<file_sep>package com.dragon.service;

import java.sql.Connection;
import java.sql.SQLException;

import com.dragon.access.AccessHelper;
import com.dragon.common.LoginRegister;
import com.dragon.dao.LoginRegisterDao;

public class LoginRegisterService {
	public static final LoginRegisterService INSTANCE = new LoginRegisterService(); // 创建单例

	private AccessHelper accessHelper = AccessHelper.INSTANCE; // 资源访问助手

	public LoginRegisterService() {

	}

	public boolean createLoginRegist(int studentId, String password) {

		// 创建数据库连接，并关闭自动提交（autoCommit）。
		Connection connection = accessHelper.createConnection(false);

		LoginRegisterDao loginRegisterDao = new LoginRegisterDao(connection);

		boolean result = false;

		try {
			if (!loginRegisterDao.retrieveLoginRegistName(studentId)) {
				result = loginRegisterDao.createLoginRegist(studentId, password);
			}
		} catch (SQLException e) {
			// 若抛出异常，需回滚事务，最好如下显式地回滚。
			rollback(connection);
			// 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
			throw new RuntimeException(e);

		} finally {
			// 关闭连接，以释放占用的资源。
			close(connection);

		}

		return result;

	}

	public boolean retrieveLoginRegistName(int studentId) {
		// 创建数据库连接，并关闭自动提交（autoCommit）。
		Connection connection = accessHelper.createConnection(false);

		LoginRegisterDao loginRegisterDao = new LoginRegisterDao(connection);

		boolean result = false;

		try {
			result = loginRegisterDao.retrieveLoginRegistName(studentId);
		} catch (SQLException e) {
			// 若抛出异常，需回滚事务，最好如下显式地回滚。
			rollback(connection);
			// 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
			throw new RuntimeException(e);

		} finally {
			// 关闭连接，以释放占用的资源。
			close(connection);

		}
		return result;
	}

	public LoginRegister retrieveLoginRegistNameAndPassword(int studentId) {

		// 创建数据库连接，并关闭自动提交（autoCommit）。
		Connection connection = accessHelper.createConnection(false);

		LoginRegisterDao loginRegisterDao = new LoginRegisterDao(connection);

		LoginRegister result = null;

		try {
			result = loginRegisterDao.retrieveLoginRegistNameAndPassword(studentId);
		} catch (SQLException e) {
			// 若抛出异常，需回滚事务，最好如下显式地回滚。
			rollback(connection);
			// 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
			throw new RuntimeException(e);

		} finally {
			// 关闭连接，以释放占用的资源。
			close(connection);

		}
		return result;

	}

	public LoginRegister retrieveLoginRegistAllByStudentId(int studentId) {
		// 创建数据库连接，并关闭自动提交（autoCommit）。
		Connection connection = accessHelper.createConnection(false);

		LoginRegisterDao loginRegisterDao = new LoginRegisterDao(connection);

		LoginRegister result = null;

		try {
			result = loginRegisterDao.retrieveLoginRegistAllByStudentId(studentId);
		} catch (SQLException e) {
			// 若抛出异常，需回滚事务，最好如下显式地回滚。
			rollback(connection);
			// 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
			throw new RuntimeException(e);

		} finally {
			// 关闭连接，以释放占用的资源。
			close(connection);

		}
		return result;
	}

	public int updateLoginRegistByStudentId(LoginRegister loginRegist) {
		// 创建数据库连接，并关闭自动提交（autoCommit）。
		Connection connection = accessHelper.createConnection(false);

		LoginRegisterDao loginRegisterDao = new LoginRegisterDao(connection);

		int result = 0;

		try {
			result = loginRegisterDao.updateLoginRegistByStudentId(loginRegist);
		} catch (SQLException e) {
			// 若抛出异常，需回滚事务，最好如下显式地回滚。
			rollback(connection);
			// 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
			throw new RuntimeException(e);
		} finally {
			// 关闭连接，以释放占用的资源。
			close(connection);
		}
		return result;
	}

	private void rollback(Connection connection) {
		try {
			connection.rollback();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private void close(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
<file_sep>package com.dragon.service;

import java.sql.Connection;
import java.sql.SQLException;

import com.dragon.access.AccessHelper;
import com.dragon.common.Management;
import com.dragon.dao.UploadDao;

public final class UploadService {
  public static final UploadService INSTANCE = new UploadService(); // 创建单例

  private AccessHelper accessHelper = AccessHelper.INSTANCE; // 资源访问助手

  public UploadService() {

  }

  public void createAll(Management management)  {

    // 创建数据库连接，并关闭自动提交（autoCommit）。
    Connection connection = accessHelper.createConnection(false);

    UploadDao UploadDao = new UploadDao(connection);

    try {
      UploadDao.createAll(management);

      // 提交事务。
      connection.commit();
    } catch (SQLException e) {
      // 若抛出异常，需回滚事务，最好如下显式地回滚。
      rollback(connection);
      // 将SQLException转化为RuntimeException，如此，该方法调用者就不需显式地处理该SQLException。
      throw new RuntimeException(e);

    } finally {
      // 关闭连接，以释放占用的资源。
      close(connection);

    }

  }

  private void rollback(Connection connection) {
    try {
      connection.rollback();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  private void close(Connection connection) {
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
<file_sep>function doOnclick() {
	document.getElementById("discussInput").style.display = "none";
	document.getElementById("discussTextarea").style.display = "block";
	document.getElementById("discussTextarea").focus();
}

function doOnblur() {
	document.getElementById("discussInput").style.display = "block";
	document.getElementById("discussTextarea").style.display = "none";
}

languages:
Java Server Pages
Java
SQL
JavaScript
CSS

repo_language: Java Server Pages


text:
<file_sep># win10_rename

文件重命名

点击后将每个文件的后缀自动更新
固定命名_月日_版本
版本名读取当前时间，不同的时间对应不同版本

branch_name: refs/heads/master

repo_language: Markdown


text:
<repo_name>ShashankSharma17/weather-api<file_sep>/README.md
# weather-api
weather api usin openweather.org


text:
<repo_name>folkengine/discovery_api<file_sep>/lib/discovery_api.ex
defmodule DiscoveryApi do
  @moduledoc false
  def instance() do
    :discovery_api
  end
end

repo_language: Elixir


text:
<file_sep><?php

namespace ExerciseBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ExerciseBundle extends Bundle
{
}

repo_language: PHP

repo_name: gdarquie/interview


text:
<repo_name>JuanAndresRomanYanez/proyecto-vits-hackbo<file_sep>/KARDEX.tpl
<form action="/ViewKardex" method="post" >
    {{Nombre}}
    {{Curso}}
    {{Paralelo}}
    {{Gestion}}
</form><file_sep>/SERVER.py
from bottle import get, post, request, run, route, redirect, template, response, static_file
import os

Administrador = {'id':[1], 'nom':['<NAME>'], 'app':['Roman'], 'apm':['Yañez'], 'usu':['adm'], 'contra':['adm'], 'img':[]}

Profesor = {'id':[1], 'nom':['Brayan'], 'app':['Torrez'], 'apm':['Navia'], 'materia':['Fisica-Quimica'], 'usu':['Enigma'], 'contra':['Enigma_eaw'], 'img':[]}

Padre = {'id':[1], 'nom':['Angel'], 'app':['Vargas'], 'apm':['Landivar'], 'usu':['pad'], 'contra':['pad'], 'img':[]}

Estudiante  = {'id':[1], 'nom':['Alexis'], 'app':['Lozano'], 'apm':['Teran'], 'curso':['1°'], 'paralelo':['B'], 'nompm':['Hugo'], 'appmp':['Lozano'], 'apmmp':['Barba'], 'usupm':['hlozano'], 'contramp':['hl123']}

def nwId():
    mayor = -1
    for x in datos['id']:
        if x > mayor:
            mayor = x
    mayor += 1
    return mayor

@route('/')
def inicio():
    return template('Index')

@route('/archivoimg/<nombrearchivo>')
def servirarchivos(nombrearchivo):
    app = os.getcwd()  # get current Windows Directory
    return static_file(nombrearchivo, root=app + "/IMAGENES")

@route('/archivocss/<nombrearchivo>')
def servirarchivos(nombrearchivo):
    app = os.getcwd()  # get current Windows Directory
    return static_file(nombrearchivo, root=app + "/CSS")

@route('/archivocssform/<nombrearchivo>')
def servirarchivos(nombrearchivo):
    app = os.getcwd()  # get current Windows Directory
    return static_file(nombrearchivo, root=app + "/CSS")

@route('/archivocssmenu/<nombrearchivo>')
def servirarchivos(nombrearchivo):
    app = os.getcwd()  # get current Windows Directory
    return static_file(nombrearchivo, root=app + "/CSS")

@route('/Iniciar')
def Login():
      return template('LOGIN')

@route('/login', method='post')
def Ingresar_Sistema():
      login = request.forms.get('log')
      password = request.forms.get('pas')
      selection = request.forms.get('select')
      if login in Administrador['usu'] and selection == '2':
              pos = Administrador['usu'].index(login)
              if password == Administrador['contra'][pos]:
                  # return "ingresaste " + usr['nom'][pos]
                  response.set_cookie("id", str(Administrador['id'][pos]))
                  return template('ADMINISTRADOR')

      elif login in Profesor['usu'] and selection == '3':
              pos = Profesor['usu'].index(login)
              if password == Profesor['contra'][pos]:
                  # return "ingresaste " + usr['nom'][pos]
                  response.set_cookie("id", str(Profesor['id'][pos]))
                  return template('PROFESOR')

      elif login in Padre['usu'] and selection == '4':
              pos = Padre['usu'].index(login)
              if password == Padre['contra'][pos]:
                  # return "ingresaste " + usr['nom'][pos]
                  response.set_cookie("id", str(Padre['id'][pos]))
                  return template('PADRES')

      print (selection)
      return redirect('/')

@route('/logout')
def salir():
    response.set_cookie("id", "-1")
    return redirect('/')

run(host='0.0.0.0', port = 8003)

languages: Smarty Python

repo_language: Smarty


text:
<repo_name>evgeniastyaglicknz/cennznet_proj<file_sep>/CenNetNzMain/CennznetAngular/CennznetAngular/ClientApp/src/app/services/context.ts
import { Project } from '../shared/classes';

export class ContextService {

  public projects: Project[];
  public paymentOngoing: boolean = false;
  public paymentSuccessfull: boolean = false;
  public showLogin: boolean = false;
  public showSignup: boolean = false;

  public userName: string | undefined;

  public tokens: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  public endpoint = 'wss://nikau.centrality.me/public/ws';

  constructor() {
    this.projects = [];
    this.addProject("p1", "Global Species Database", "2021-08-22", "donate","IUCN Photo1.jpg", 10);
    this.addProject("p2", "Environmental Coding School", "2021-09-04", "invest", "GirlCodeIncubator1.jpg", 15);
  }

  public addProject(
    code: string,
    name: string,
    releaseDate: string,
    type: string,
    url: string,
    price: number  ) {
    let proj = new Project();
    proj.name = name;
    proj.code = code;
    proj.url = url;
    proj.type = type;
    proj.releaseDate = releaseDate;
    proj.price = price;
    this.projects.push(proj);
  }

  public readCollection() {

  }

}
<file_sep>/CennznetAngular/CennznetAngular/ClientApp/src/app/shared/classes.ts
export class Project {
  name: string;
  url: string;
  code: string;
  releaseDate: string;
  type: string;
  price: number;
}
<file_sep>/CenNetNzMain/CennznetAngular/CennznetAngular/ClientApp/src/app/management/management.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { ContextService } from '../services/context';
import { Project } from '../shared/classes';

@Component({
  selector: 'management',
  templateUrl: './management.component.html',
  styleUrls: ['./management.component.css']
})
export class ManagementComponent {

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string, public context: ContextService) {
  }

  releaseTokensForProject(name: string) {
    alert("Tokens are being released for the project: " + name);
  }
}

<file_sep>/CenNetNzMain/CennznetAngular/CennznetAngular/ClientApp/src/app/home/home.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { ContextService } from '../services/context';
import { Project } from '../shared/classes';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls:  ['./home.component.css']
})
export class HomeComponent {

  selectedProject: Project | undefined;

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string, public context: ContextService) {
  }

  showPayment(p: Project) {
    this.selectedProject = p;
    this.context.paymentOngoing = true;
  }

  closePayment(pay: boolean) {
    this.context.paymentOngoing = false;
    if (pay && this.selectedProject) {
      this.context.paymentSuccessfull = true;
    }
  }

  closeSuccess() {
    this.context.paymentSuccessfull = false;
  }
}

<file_sep>/CennznetAngular/CennznetAngular/Pages/_ViewImports.cshtml
@using CennznetAngular
@namespace CennznetAngular.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<file_sep>/CennznetAngular/CennznetAngular/ClientApp/src/app/nav-menu/nav-menu.component.ts
import { Component } from '@angular/core';
import { ContextService } from '../services/context';

@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
  isExpanded = false;

  userName: string = '';

  constructor(public context: ContextService) {
  }

  collapse() {
    this.isExpanded = false;
  }

  toggle() {
    this.isExpanded = !this.isExpanded;
  }

  login() {
    this.context.userName = this.userName;
    this.closeSignup();
    this.closeLogin();
  }

  cancelLogin() {
    this.closeSignup();
    this.closeLogin();
  }

  showLogin() {
    this.context.showLogin = true;
  }

  showSignup() {
    this.context.showSignup = true;
  }

  closeSignup() {
    this.context.showSignup = false;
  }

  closeLogin() {
    this.context.showLogin = false;
  }
}

languages: HTML+Razor TypeScript

repo_language: HTML+Razor


text:
<repo_name>Rajiv5055/Facerecognition-frontend<file_sep>/src/components/Profile/Profile.js
import React from 'react';
import profile from './profile.png';
const Profile = ({ name, email, entries, joined, onRouteChange }) => {
	return(

            <fieldset id="sign_up" className="ba b--transparent ph0 mh0">

Profile

 Name:

 {name}

 Email:

 {email}

 Entries Done:

 {entries}

 Joined:

 {joined}

            </fieldset>

              <input
                className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
                type="submit"
                value="Back"
                onClick={() => onRouteChange('home')}
              />

	);
}

export default Profile;<file_sep>/src/components/Footer.js
import React from 'react';
import Link from '@material-ui/core/Link';
import GitHubIcon from '@material-ui/icons/GitHub';
import FacebookIcon from '@material-ui/icons/Facebook';
import InstagramIcon from '@material-ui/icons/Instagram';
import LinkedInIcon from '@material-ui/icons/LinkedIn';
import Typography from '@material-ui/core/Typography';

const Footer = () =>{
   return(

 CopyRight ©<Link href="https://rajiv5055.github.io/portfolio/Portfolio/index.html" color="textSecondary"><NAME></Link>

   	    <Link variant="body1" color="textSecondary" href="https://github.com/Rajiv5055">
          <GitHubIcon />
        </Link>
        <Link variant="body1" color="textSecondary" href="https://www.instagram.com/rajeev__nayan/?hl=en">
         <InstagramIcon />
        </Link>
        <Link variant="body1" color="textSecondary" href="https://www.facebook.com/profile.php?id=100008857086332">
          <FacebookIcon />
        </Link>
        <Link variant="body1" color="textSecondary" href="https://www.linkedin.com/in/rajiv-nayan-62a791146/">
          <LinkedInIcon />
        </Link>

   );
}

export default Footer;<file_sep>/src/components/Navigation/Navigation.js
import React from 'react';
import profile from './profile.png';
import register from './register.png';
import signin from './signin.jpg';
import signout from './signout.jpg';
import Logo from '../Logo/Logo.js';
const Navigation = ({ onRouteChange, isSignedIn }) => {
    if (isSignedIn) {
      return (

          <Logo />

 onRouteChange('profile')} style={{paddingRight: "20px"}} className='f3 link dim black underline pointer'>

Profile

 onRouteChange('signin')} className='f3 link dim black underline pointer'>

Sign Out

      );
    } else {
      return (

          <Logo />

 onRouteChange('signin')} style={{paddingRight: "20px"}} className='f3 link dim black underline pointer'>

Sign In

 onRouteChange('register')} className='f3 link dim black underline pointer'>

Register

      );
    }
}

export default Navigation;<file_sep>/README.md
# Facerecogntion-frontend
 [https://smart-facedetect1.herokuapp.com/](https://smart-facedetect1.herokuapp.com/)

1. Clone this repo
2. Run `npm install`
3. Run `npm start`

# backend sorce code
 [click here](https://github.com/Rajiv5055/Facerecognition-backend)

 Demo Links :
 1) https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260
 2) https://images.pexels.com/photos/2691608/pexels-photo-2691608.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940
 3) https://images.pexels.com/photos/5588209/pexels-photo-5588209.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500
 4) https://images.pexels.com/photos/415829/pexels-photo-415829.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500
 5) https://images.pexels.com/photos/573299/pexels-photo-573299.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500

branch_name: refs/heads/main

languages: Markdown JavaScript


text:
<file_sep># frozen_string_literal: true

require 'eksekuter'

RSpec.describe 'EksekResult#to_s' do
  it 'returns the stdout' do
    command = 'printf HelloStdout && printf HelloStderr >&2'
    output = "The output was: #{Eksekuter.new.capture(command)}."
    expect(output).to eq('The output was: HelloStdout.')
  end
end
<file_sep>Gem::Specification.new do |s|
  s.name = 'eksek'
  s.version = '0.3.0'
  s.authors = ['<NAME>', '<NAME>']
  s.homepage = 'https://github.com/taccon/eksek'
  s.summary = 'A better backticks'
  s.description = <<~END
    Execute shell commands and easily get stdout, stderr, exit code, and more
  END
  s.license = 'ISC'

  s.files = Dir['.gemspec', 'lib/**/*.rb', 'license.txt', 'readme.md']

  s.required_ruby_version = '~> 2.3'
  s.add_development_dependency 'rspec','~> 3'
  s.add_development_dependency 'rubocop', '~> 0.49.0'
end
<file_sep># frozen_string_literal: true

require_relative 'eksek_error'

# Describes a result object to be used for evaluating
# return values from a command
class EksekResult
  def initialize env, cmd, exit_code, out_stream, err_stream
    @env = env
    @cmd = cmd
    @exit_code = exit_code
    @out_stream = out_stream
    @err_stream = err_stream
  end
  # rubocop:enable Metrics/ParameterLists

  attr_reader :exit_code

  def stdout
    @stdout ||= @out_stream&.read
  end

  def stderr
    @stderr ||= @err_stream&.read
  end

  def success?
    @exit_code.zero?
  end

  def success!
    raise EksekError, "Command failed: #{@cmd.inspect}" unless success?
    self
  end

  def to_s
    stdout
  end
end
<file_sep># frozen_string_literal: true

require_relative 'eksekuter'

# Executes shell commands and can be specified to return the standard output,
# standard error, etc.
# Accepts the same options as Process.spawn e.g. :chdir, :env.
module Kernel
  private

  def eksek *args, **opts, &block
    Eksekuter.new.exec(*args, **opts, &block)
  end

  def eksek! *args, **opts, &block
    eksek(*args, **opts, &block).success!
  end

  def eksek? *args, **opts, &block
    eksek(*args, **opts, &block).success?
  end

  def kapture *args, **opts, &block
    Eksekuter.new.capture(*args, **opts, &block)
  end

  def kapture! *args, **opts, &block
    kapture(*args, **opts, &block).success!
  end

  def kapture? *args, **opts, &block
    kapture(*args, **opts, &block).success?
  end
end
<file_sep># frozen_string_literal: true

# Represents an error in the executio of a system call when success! was
# required.
class EksekError < StandardError
end
<file_sep># frozen_string_literal: true

require 'open3'

require_relative 'eksek_result'

# Class that command execution is delegated to by Eksek.
class Eksekuter
  # @param {Logger} logger
  def initialize logger: nil
    @logger = logger
    @stdout_buffer = nil
    @stderr_buffer = nil
    @stdin_buffer = nil
  end

  # Wraps around Kernel#spawn so that the return value is an EksekResult.
  # @return EksekResult
  def exec *args, **opts
    env, cmd = split_env_and_cmd(args)
    params = { env: env, cmd: cmd, opts: opts }
    process_status = spawn_and_get_status(params)
    assemble_result(params, process_status)
  end

  # Like Eksekuter#exec but the :out and :err options are ignored; instead
  # the output is attached to the EksekResult object returned.
  # Returns an EksekResult object which getters :stdout and :stderr containing
  # the corresponding output of the spawned process.
  # @return EksekResult
  def capture *args, **opts
    env, cmd = split_env_and_cmd(args)
    out_read, out_write = IO.pipe
    err_read, err_write = IO.pipe
    opts2 = opts.merge(out: out_write, err: err_write)
    params = { env: env, cmd: cmd, opts: opts2 }
    process_status = spawn_and_get_status(params)
    out_write.close
    err_write.close
    assemble_result(params, process_status, out_read, err_read)
  end

  private

  def split_env_and_cmd args
    cmd_args = args.clone
    env = cmd_args.first.is_a?(Hash) ? cmd_args.shift : {}
    env = env.each_with_object({}) { |(k, v), o| o[k.to_s] = v }
    cmd = cmd_args.size == 1 ? cmd_args.first : cmd_args
    [env, cmd]
  end

  def spawn_and_get_status params
    env = params.fetch(:env)
    cmd = params.fetch(:cmd)
    opts = params.fetch(:opts)
    pid = spawn(env, *cmd, opts)
    _, process_status = Process.wait2(pid)
    process_status
  end

  def assemble_result params, process_status, out_stream = nil, err_stream = nil
    EksekResult.new(
      params.fetch(:env),
      params.fetch(:cmd),
      process_status.exitstatus,
      out_stream,
      err_stream,
    )
  end
end
<file_sep># eksek

[![Travis](https://img.shields.io/travis/taccon/eksek.svg)](https://travis-ci.org/taccon/eksek)
[![Coverage Status](https://coveralls.io/repos/github/taccon/eksek/badge.svg?branch=coveralls)](https://coveralls.io/github/taccon/eksek?branch=coveralls)

`eksek` is a library to run shell commands synchronously and obtain any of the standard output, standard error, and exit code with flexibility.

## Features

### Basic usage

Use the `eksek` method to execute a command:

```ruby
eksek 'echo Hello'
```

or the `kapture` method to execute a command but "capture" the standard output and standard error in a fashion similar to `Kernel#\`` (backticks) or `%x()`.

```ruby
kapture 'echo Hello'
```

These methods return an `EksekResult` object providing the following methods:

- `exit` returns the exit code.
- `stdout` returns the standard output as a string if `kapture` was called.
- `stderr` returns the standard error as a string if `kapture` was called.
- `success?` returns `true` or `false` depending of the exit code (`0` for `true`).
- `success!` throws an exception if the command exited with a non-0 code.

The `success!` method can be chained with any other of the above ones and it is wrapped in the convenience method `eksek!` to have a "fail or return" like so:

```ruby
puts eksek!('echo Hello').stdout # Hello

# The above is essentially the same as:

puts eksek('echo Hello').success!.stdout
```

### Passing other options

`eksek` has the same signature as `Process#spawn`. This means that:

- the first parameter can optionally be a hash, passed as the process environment;
- the command can be passed as a single string or as variable-length arguments;
- other options can be passed as hash arguments.

Additionally, the environment will have its keys stringified, so that symbols can be used too. For example:

```ruby
r = eksek { A: 'Hello' }, 'echo $A'
puts r.stdout # Hello

r = eksek 'echo', 'Hello'
puts r.stdout # Hello

r = eksek 'echo $PWD', chdir: '/tmp'
puts r.stdout # /tmp
```

### Further information

In case you prefer an object oriented method, you can also use the `Eksekuter` class that is used by the `eksek` method directly. The following examples are basically the same:

```ruby
# With eksek
eksek 'echo Hello'
kapture 'echo Hello'

# With Eksekuter
Eksekuter.new.exec('echo Hello')
Eksekuter.new.capture('echo Hello')
```
<file_sep># frozen_string_literal: true

require 'eksek'
require 'eksekuter'

RSpec.describe 'Eksekuter success methods' do
  it 'returns true or false depending on the exit code' do
    expect(Eksekuter.new.exec('true').success?).to be(true)
    expect(Eksekuter.new.exec('exit 1').success?).to be(false)
  end

  it 'fails when appropriate' do
    expect { Eksekuter.new.exec('true').success! }.not_to raise_error
    expect { Eksekuter.new.exec('exit 1').success! }.to raise_error EksekError
  end

  it 'returns the exit code' do
    expect(Eksekuter.new.exec('exit 0').exit_code).to be(0)
    expect(Eksekuter.new.exec('exit 1').exit_code).to be(1)
    expect(Eksekuter.new.exec('exit 7').exit_code).to be(7)
  end
end

RSpec.describe 'Eksekuter#capture' do
  it 'captures the stdout and stderr separately' do
    expect(Eksekuter.new.capture('printf Hello').stdout)
      .to eq('Hello')
    expect(Eksekuter.new.capture('printf Hello >&2').stderr)
      .to eq('Hello')
  end
end

RSpec.describe 'Eksekuter with overridden output streams' do
  it 'can write to a custom IO object' do
    readable, writable = IO.pipe
    Eksekuter.new.exec('printf Hello', out: writable)
    writable.close
    expect(readable.read).to eq('Hello')
  end

  it 'can read from a custom IO object' do
    readable, writable = IO.pipe
    writable.write 'Hello'
    writable.close
    expect(Eksekuter.new.capture('read A; printf $A', in: readable).stdout)
      .to eq('Hello')
  end
end

RSpec.describe 'Standard input' do
  it 'can write to a custom IO object' do
    readable, writable = IO.pipe
    Eksekuter.new.exec('printf Hello', out: writable)
    writable.close
    expect(readable.read).to eq('Hello')
  end

  it 'can read from a custom IO object' do
    readable, writable = IO.pipe
    writable.write 'Hello'
    writable.close
    expect(Eksekuter.new.capture('read A; printf $A', in: readable).stdout)
      .to eq('Hello')
  end
end

RSpec.describe 'Kernel#spawn-style parameters' do
  it 'accepts a Hash as an optional first parameter' do
    result = Eksekuter.new
      .capture({ 'TEXT' => 'Hello' }, 'printf $TEXT')
    expect(result.stdout).to eq('Hello')
  end

  it 'stringifies the keys of the environment' do
    result = Eksekuter.new
      .capture({ TEXT: 'Hello' }, 'printf $TEXT')
    expect(result.stdout).to eq('Hello')
  end

  it 'accepts a variable-length parameter list as command' do
    result = Eksekuter.new
      .capture('echo', 'Hello', 'World')
    expect(result.stdout).to eq("Hello World\n")
  end
end

languages: Markdown Ruby

repo_name: taccon/eksek