id stringlengths 27 31 | content stringlengths 14 287k | max_stars_repo_path stringlengths 52 57 |
|---|---|---|
crossvul-java_data_bad_1902_0 | package com.bijay.onlinevotingsystem.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bijay.onlinevotingsystem.dao.AdminDao;
import com.bijay.onlinevotingsystem.dao.AdminDaoImpl;
@WebServlet("/aLoginController")
public class AdminLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
AdminDao adminDao = new AdminDaoImpl();
SHA256 sha = new SHA256();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp");
request.setAttribute("loggedOutMsg", "Log Out Successful");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
String userName = request.getParameter("aname");
String password = sha.getSHA(request.getParameter("pass"));
// String password = request.getParameter("pass");
String rememberMe = request.getParameter("remember-me");
// validation
if (adminDao.loginValidate(userName, password)) {
if (rememberMe != null) {
Cookie cookie1 = new Cookie("uname", userName);
Cookie cookie2 = new Cookie("pass", password);
cookie1.setMaxAge(24 * 60 * 60);
cookie2.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
response.addCookie(cookie2);
}
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
/*
* RequestDispatcher rd =
* request.getRequestDispatcher("AdminController?actions=admin_list");
* rd.forward(request, response);
*/
response.sendRedirect("AdminController?actions=admin_list");
} else {
RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Username or Password !!");
rd.include(request, response);
}
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/bad_1902_0 |
crossvul-java_data_bad_1902_2 | package com.bijay.onlinevotingsystem.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.bijay.onlinevotingsystem.dao.VoterDao;
import com.bijay.onlinevotingsystem.dao.VoterDaoImpl;
@WebServlet("/vLoginController")
public class VoterLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
VoterDao voterDao = new VoterDaoImpl();
SHA256 sha = new SHA256();
private String host;
private String port;
private String user;
private String pass;
public String recipient;
public int otp;
public int giveOtp() {
return this.otp;
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
public VoterLoginController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* one servlet le another servlet ma request garda doGet() ma aauxa. so for
* logout, session use garera login page ma dispatch garxau.
*/
HttpSession session = request.getSession();
session.invalidate();
RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp");
request.setAttribute("loggedOutMsg", "Log Out Successful !!");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
// HttpSession session=request.getSession();
PrintWriter out = response.getWriter();
int min = 100000;
int max = 999999;
otp = 5432;
Random r = new Random();
otp = r.nextInt(max - min) + min;
String userName = request.getParameter("uname");
String password = sha.getSHA(request.getParameter("pass"));
String vemail = request.getParameter("vmail");
String recipient = vemail;
String subject = "otp verification";
String content = "your otp is: " + otp;
// System.out.print(recipient);
String resultMessage = "";
// validation
if (voterDao.loginValidate(userName, password, vemail)) {
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
try {
EmailSend.sendEmail(host, port, user, pass, recipient, subject, content);
} catch (MessagingException e) {
e.printStackTrace();
resultMessage = "There were an error: " + e.getMessage();
} finally {
RequestDispatcher rd = request.getRequestDispatcher("OTP.jsp");
rd.include(request, response);
out.println("<script type=\"text/javascript\">");
out.println("alert('" + resultMessage + "');");
out.println("</script>");
}
} else {
RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Input ! Enter again !!");
// request.setAttribute("forgotPassMsg", "Forgot password??");
rd.include(request, response);
/*
* String forgetpass = request.getParameter("forgotPass"); //
* System.out.println(forgetpass); if (forgetpass == null) { rd =
* request.getRequestDispatcher("resetPassword.jsp"); rd.forward(request,
* response);
*/
}
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/bad_1902_2 |
crossvul-java_data_good_1902_0 | package com.bijay.onlinevotingsystem.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bijay.onlinevotingsystem.dao.AdminDao;
import com.bijay.onlinevotingsystem.dao.AdminDaoImpl;
@WebServlet("/aLoginController")
public class AdminLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
AdminDao adminDao = new AdminDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp");
request.setAttribute("loggedOutMsg", "Log Out Successful");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
String userName = request.getParameter("aname");
String password = request.getParameter("pass");
// String password = request.getParameter("pass");
String rememberMe = request.getParameter("remember-me");
// validation
if (adminDao.loginValidate(userName, password)) {
if (rememberMe != null) {
Cookie cookie1 = new Cookie("uname", userName);
Cookie cookie2 = new Cookie("pass", password);
cookie1.setMaxAge(24 * 60 * 60);
cookie2.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
response.addCookie(cookie2);
}
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
/*
* RequestDispatcher rd =
* request.getRequestDispatcher("AdminController?actions=admin_list");
* rd.forward(request, response);
*/
response.sendRedirect("AdminController?actions=admin_list");
} else {
RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Username or Password !!");
rd.include(request, response);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-759/java/good_1902_0 |
crossvul-java_data_good_1902_1 | package com.bijay.onlinevotingsystem.controller;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class SHA256 {
private static final String SSHA_PREFIX = "{SSHA}";
private static final int SSHA_256_LENGTH = 32; // SHA-256 is 32 bytes long
private static final int SALT_LENGTH = 16; // Use a 16 byte salt
public String getSHA(String password) {
try {
byte[] salt = getSalt();
String cipher = getCipher(password, salt);
return cipher;
// For specifying wrong message digest algorithms
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static boolean validatePassword(String password, String cipherText) {
boolean isValid = false;
try {
String cipher = cipherText.substring(SSHA_PREFIX.length());
byte[] cipherBytes = Base64.getDecoder().decode(cipher.getBytes());
byte[] salt = new byte[SALT_LENGTH];
System.arraycopy(cipherBytes, SSHA_256_LENGTH, salt, 0, SALT_LENGTH);
String result = getCipher(password, salt);
//Compare the newly hashed password taking the same salt with the input hash
isValid = result.equals(cipherText);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return isValid;
}
private static byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_LENGTH];
random.nextBytes(salt);
return salt;
}
private static String getCipher(String password, byte[] salt) throws NoSuchAlgorithmException {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
byte[] passBytes = password.getBytes();
byte[] allBytes = new byte[passBytes.length + SALT_LENGTH];
System.arraycopy(passBytes, 0, allBytes, 0, passBytes.length);
System.arraycopy(salt, 0, allBytes, passBytes.length, SALT_LENGTH);
byte[] cipherBytes = new byte[SSHA_256_LENGTH + SALT_LENGTH];
// digest() method called
// to calculate message digest of an input
// and return array of byte
byte[] messageDigest = md.digest(allBytes);
System.arraycopy(messageDigest, 0, cipherBytes, 0, SSHA_256_LENGTH);
System.arraycopy(salt, 0, cipherBytes, SSHA_256_LENGTH, SALT_LENGTH);
String result = SSHA_PREFIX + Base64.getEncoder().encodeToString(cipherBytes);
return result;
}
}
| ./CrossVul/dataset_final_sorted/CWE-759/java/good_1902_1 |
crossvul-java_data_good_1902_3 | package com.bijay.onlinevotingsystem.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
import com.bijay.onlinevotingsystem.controller.SHA256;
import com.bijay.onlinevotingsystem.dto.Admin;
import com.bijay.onlinevotingsystem.util.DbUtil;
public class AdminDaoImpl implements AdminDao {
PreparedStatement ps = null;
@Override
public void saveAdminInfo(Admin admin) {
String sql = "insert into admin_table(admin_name, password) values(?,?)";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, admin.getAdminName());
ps.setString(2, admin.getPassword());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Admin> getAllAdminInfo() {
List<Admin> adminList = new ArrayList<>();
String sql = "select * from admin_table";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Admin admin = new Admin();
admin.setId(rs.getInt("id"));
admin.setAdminName(rs.getString("admin_name"));
admin.setPassword(rs.getString("password"));
adminList.add(admin);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return adminList;
}
@Override
public void deleteAdminInfo(int id) {
String sql = "delete from admin_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public Admin getAdminInfoById(int id) {
Admin admin = new Admin();
String sql = "select * from admin_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
admin.setId(rs.getInt("id"));
admin.setAdminName(rs.getString("admin_name"));
admin.setPassword(rs.getString("password"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return admin;
}
@Override
public void updateAdminInfo(Admin admin) {
String sql = "update admin_table set admin_name=?, password=? where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, admin.getAdminName());
ps.setString(2, admin.getPassword());
ps.setInt(3, admin.getId());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean loginValidate(String userName, String password) {
String sql = "select * from admin_table where admin_name=?";
try {
ps=DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ResultSet rs =ps.executeQuery();
if (rs.next()) {
String cipherText = rs.getString("password");
return SHA256.validatePassword(password, cipherText);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/good_1902_3 |
crossvul-java_data_good_1902_2 | package com.bijay.onlinevotingsystem.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.bijay.onlinevotingsystem.dao.VoterDao;
import com.bijay.onlinevotingsystem.dao.VoterDaoImpl;
@WebServlet("/vLoginController")
public class VoterLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
VoterDao voterDao = new VoterDaoImpl();
private String host;
private String port;
private String user;
private String pass;
public String recipient;
public int otp;
public int giveOtp() {
return this.otp;
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
public VoterLoginController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* one servlet le another servlet ma request garda doGet() ma aauxa. so for
* logout, session use garera login page ma dispatch garxau.
*/
HttpSession session = request.getSession();
session.invalidate();
RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp");
request.setAttribute("loggedOutMsg", "Log Out Successful !!");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
// HttpSession session=request.getSession();
PrintWriter out = response.getWriter();
int min = 100000;
int max = 999999;
otp = 5432;
Random r = new Random();
otp = r.nextInt(max - min) + min;
String userName = request.getParameter("uname");
String password = request.getParameter("pass");
String vemail = request.getParameter("vmail");
String recipient = vemail;
String subject = "otp verification";
String content = "your otp is: " + otp;
// System.out.print(recipient);
String resultMessage = "";
// validation
if (voterDao.loginValidate(userName, password, vemail)) {
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
try {
EmailSend.sendEmail(host, port, user, pass, recipient, subject, content);
} catch (MessagingException e) {
e.printStackTrace();
resultMessage = "There were an error: " + e.getMessage();
} finally {
RequestDispatcher rd = request.getRequestDispatcher("OTP.jsp");
rd.include(request, response);
out.println("<script type=\"text/javascript\">");
out.println("alert('" + resultMessage + "');");
out.println("</script>");
}
} else {
RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Input ! Enter again !!");
// request.setAttribute("forgotPassMsg", "Forgot password??");
rd.include(request, response);
/*
* String forgetpass = request.getParameter("forgotPass"); //
* System.out.println(forgetpass); if (forgetpass == null) { rd =
* request.getRequestDispatcher("resetPassword.jsp"); rd.forward(request,
* response);
*/
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-759/java/good_1902_2 |
crossvul-java_data_bad_2031_10 | package org.jolokia.restrictor;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.InputStream;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
/**
* @author roland
* @since Jul 29, 2009
*/
public class PolicyBasedRestrictorTest {
@Test
public void basics() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"Verbose"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"Verbose"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"),"gc"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Threading"),"gc"));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.POST));
assertFalse(restrictor.isHttpMethodAllowed(HttpMethod.GET));
}
@Test
public void restrictIp() {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
String ips[][] = {
{ "11.0.18.32", "true" },
{ "planck", "true" },
{ "heisenberg", "false" },
{ "10.0.11.125", "true" },
{ "10.0.11.126", "false" },
{ "11.1.18.32", "false" },
{ "192.168.15.3", "true" },
{ "192.168.15.8", "true" },
{ "192.168.16.3", "false" }
};
for (String check[] : ips) {
String res = restrictor.isRemoteAccessAllowed(check[0]) ? "true" : "false";
assertEquals("Ip " + check[0] + " is " +
(check[1].equals("false") ? "not " : "") +
"allowed",check[1],res);
}
}
@Test
public void patterns() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config,name=Bla"),"Debug"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("jolokia:type=Threading"),"gc"));
// No hosts set.
assertTrue(restrictor.isRemoteAccessAllowed("10.0.1.125"));
}
@Test
public void noRestrictions() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config,name=Bla"),"Debug"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("jolokia:type=Threading"),"gc"));
assertTrue(restrictor.isTypeAllowed(RequestType.READ));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.POST));
}
@Test
public void deny() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample4.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"BlaUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config"),"Debug"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"),"gc"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"),"xavier"));
}
@Test
public void allow() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample5.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "BlaUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config"), "Debug"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "gc"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "xavier"));
}
@Test
public void illegalXml() {
InputStream is = getClass().getResourceAsStream("/illegal1.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
//ok
}
try {
new PolicyRestrictor(null);
fail("No file given");
} catch (SecurityException exp) {
// ok
}
}
@Test
public void noName() {
InputStream is = getClass().getResourceAsStream("/illegal2.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
}
}
@Test
public void invalidTag() {
InputStream is = getClass().getResourceAsStream("/illegal3.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
assertTrue(exp.getMessage().contains("attribute"));
assertTrue(exp.getMessage().contains("operation"));
assertTrue(exp.getMessage().contains("bla"));
}
}
@Test
public void doubleName() {
InputStream is = getClass().getResourceAsStream("/illegal4.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
}
}
@Test
public void httpMethod() {
InputStream is = getClass().getResourceAsStream("/method.xml");
PolicyRestrictor res = new PolicyRestrictor(is);
assertTrue(res.isHttpMethodAllowed(HttpMethod.GET));
assertTrue(res.isHttpMethodAllowed(HttpMethod.POST));
}
@Test
public void illegalHttpMethod() {
InputStream is = getClass().getResourceAsStream("/illegal5.xml");
try {
new PolicyRestrictor(is);
fail();
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("BLA"));
}
}
@Test
public void illegalHttpMethodTag() {
InputStream is = getClass().getResourceAsStream("/illegal6.xml");
try {
new PolicyRestrictor(is);
fail();
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("method"));
assertTrue(exp.getMessage().contains("blubber"));
}
}
@Test
public void cors() {
InputStream is = getClass().getResourceAsStream("/allow-origin1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertFalse(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
}
@Test
public void corsWildCard() {
InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
}
@Test
public void corsEmpty() {
InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
}
@Test
public void corsNoTags() {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_10 |
crossvul-java_data_good_2031_6 | package org.jolokia.restrictor.policy;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.w3c.dom.*;
/**
* Check for location restrictions for CORS based cross browser platform requests
*
* @author roland
* @since 07.04.12
*/
public class CorsChecker extends AbstractChecker<String> {
private boolean strictChecking = false;
private List<Pattern> patterns;
/**
* Constructor buiilding up this checker from the XML document provided.
* CORS sections look like
* <pre>
* <cors>
* <allow-origin>http://jolokia.org<allow-origin>
* <allow-origin>*://*.jmx4perl.org>
*
* <strict-checking/>
* </cors>
* </pre>
*
* @param pDoc the overall policy documents
*/
public CorsChecker(Document pDoc) {
NodeList corsNodes = pDoc.getElementsByTagName("cors");
if (corsNodes.getLength() > 0) {
patterns = new ArrayList<Pattern>();
for (int i = 0; i < corsNodes.getLength(); i++) {
Node corsNode = corsNodes.item(i);
NodeList nodes = corsNode.getChildNodes();
for (int j = 0;j <nodes.getLength();j++) {
Node node = nodes.item(j);
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
assertNodeName(node,"allow-origin","strict-checking");
if (node.getNodeName().equals("allow-origin")) {
String p = node.getTextContent().trim().toLowerCase();
p = Pattern.quote(p).replace("*", "\\E.*\\Q");
patterns.add(Pattern.compile("^" + p + "$"));
} else if (node.getNodeName().equals("strict-checking")) {
strictChecking = true;
}
}
}
}
}
/** {@inheritDoc} */
@Override
public boolean check(String pArg) {
return check(pArg,false);
}
public boolean check(String pOrigin, boolean pIsStrictCheck) {
// Method called during strict checking but we have not configured that
// So the check passes always.
if (pIsStrictCheck && !strictChecking) {
return true;
}
if (patterns == null || patterns.size() == 0) {
return true;
}
for (Pattern pattern : patterns) {
if (pattern.matcher(pOrigin).matches()) {
return true;
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_6 |
crossvul-java_data_good_5842_3 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import java.util.SortedSet;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.projectforge.Version;
import org.projectforge.continuousdb.UpdateEntry;
import org.projectforge.continuousdb.UpdatePreCheckStatus;
import org.projectforge.web.HtmlHelper;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.CheckBoxPanel;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.MyComponentsRepeater;
public class SystemUpdateForm extends AbstractForm<SystemUpdateForm, SystemUpdatePage>
{
private static final long serialVersionUID = 2492737003121592489L;
protected WebMarkupContainer scripts;
public boolean showOldUpdateScripts;
private GridBuilder gridBuilder;
/**
* Cross site request forgery token.
*/
private final CsrfTokenHandler csrfTokenHandler;
/**
* List to create content menu in the desired order before creating the RepeatingView.
*/
protected MyComponentsRepeater<SingleButtonPanel> actionButtons;
public SystemUpdateForm(final SystemUpdatePage parentPage)
{
super(parentPage);
csrfTokenHandler = new CsrfTokenHandler(this);
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newGridPanel();
{
final FieldsetPanel fs = gridBuilder.newFieldset("Show all");
fs.add(new CheckBoxPanel(fs.newChildId(), new PropertyModel<Boolean>(this, "showOldUpdateScripts"), null, true) {
/**
* @see org.projectforge.web.wicket.flowlayout.CheckBoxPanel#onSelectionChanged(java.lang.Boolean)
*/
@Override
protected void onSelectionChanged(final Boolean newSelection)
{
parentPage.refresh();
}
});
}
scripts = new WebMarkupContainer("scripts");
add(scripts);
updateEntryRows();
actionButtons = new MyComponentsRepeater<SingleButtonPanel>("buttons");
add(actionButtons.getRepeatingView());
{
final Button refreshButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("refresh")) {
@Override
public final void onSubmit()
{
parentPage.refresh();
}
};
final SingleButtonPanel refreshButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), refreshButton, "refresh",
SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(refreshButtonPanel);
setDefaultButton(refreshButton);
}
}
@SuppressWarnings("serial")
protected void updateEntryRows()
{
scripts.removeAll();
final RepeatingView scriptRows = new RepeatingView("scriptRows");
scripts.add(scriptRows);
final SortedSet<UpdateEntry> updateEntries = parentPage.myDatabaseUpdater.getSystemUpdater().getUpdateEntries();
if (updateEntries == null) {
return;
}
boolean odd = true;
for (final UpdateEntry updateEntry : updateEntries) {
if (showOldUpdateScripts == false && updateEntry.getPreCheckStatus() == UpdatePreCheckStatus.ALREADY_UPDATED) {
continue;
}
final Version version = updateEntry.getVersion();
final WebMarkupContainer item = new WebMarkupContainer(scriptRows.newChildId());
scriptRows.add(item);
if (odd == true) {
item.add(AttributeModifier.append("class", "odd"));
} else {
item.add(AttributeModifier.append("class", "even"));
}
odd = !odd;
item.add(new Label("regionId", updateEntry.getRegionId()));
if (updateEntry.isInitial() == true) {
item.add(new Label("version", "initial"));
} else {
item.add(new Label("version", version.toString()));
}
final String description = updateEntry.getDescription();
item.add(new Label("description", StringUtils.isBlank(description) == true ? "" : description));
item.add(new Label("date", updateEntry.getDate()));
final String preCheckResult = updateEntry.getPreCheckResult();
item.add(new Label("preCheckResult", HtmlHelper.escapeHtml(preCheckResult, true)));
if (updateEntry.getPreCheckStatus() == UpdatePreCheckStatus.READY_FOR_UPDATE) {
final Button updateButton = new Button("button", new Model<String>("update")) {
@Override
public final void onSubmit()
{
parentPage.update(updateEntry);
}
};
item.add(new SingleButtonPanel("update", updateButton, "update"));
} else {
final String runningResult = updateEntry.getRunningResult();
item.add(new Label("update", HtmlHelper.escapeHtml(runningResult, true)));
}
}
}
/**
* @see org.projectforge.web.wicket.AbstractForm#onBeforeRender()
*/
@Override
public void onBeforeRender()
{
super.onBeforeRender();
actionButtons.render();
}
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_3 |
crossvul-java_data_good_5842_10 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.fibu;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.convert.IConverter;
import org.projectforge.common.NumberHelper;
import org.projectforge.core.Constants;
import org.projectforge.core.CurrencyFormatter;
import org.projectforge.core.NumberFormatter;
import org.projectforge.fibu.AbstractRechnungsPositionDO;
import org.projectforge.fibu.EingangsrechnungsPositionDO;
import org.projectforge.fibu.ProjektDO;
import org.projectforge.fibu.RechnungDO;
import org.projectforge.fibu.RechnungsPositionDO;
import org.projectforge.fibu.kost.Kost1DO;
import org.projectforge.fibu.kost.Kost2DO;
import org.projectforge.fibu.kost.Kost2Dao;
import org.projectforge.fibu.kost.KostZuweisungDO;
import org.projectforge.fibu.kost.KostZuweisungenCopyHelper;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.WicketAjaxUtils;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.components.MinMaxNumberField;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.converter.CurrencyConverter;
import org.projectforge.web.wicket.flowlayout.ButtonPanel;
import org.projectforge.web.wicket.flowlayout.IconButtonPanel;
import org.projectforge.web.wicket.flowlayout.IconType;
import org.projectforge.web.wicket.flowlayout.MyAjaxComponentHolder;
/**
* @author Kai Reinhard (k.reinhard@micromata.de)
*
*/
public class RechnungCostEditTablePanel extends Panel
{
private static final long serialVersionUID = -5732520730823126042L;
private final RepeatingView rows;
private final Form<AbstractRechnungsPositionDO> form;
private final FeedbackPanel feedbackPanel;
@SpringBean(name = "kost2Dao")
private Kost2Dao kost2Dao;
private AbstractRechnungsPositionDO position;
MyAjaxComponentHolder ajaxComponents = new MyAjaxComponentHolder();
/**
* Cross site request forgery token.
*/
private final CsrfTokenHandler csrfTokenHandler;
/**
* @param id
*/
@SuppressWarnings("serial")
public RechnungCostEditTablePanel(final String id)
{
super(id);
feedbackPanel = new FeedbackPanel("feedback");
ajaxComponents.register(feedbackPanel);
add(feedbackPanel);
this.form = new Form<AbstractRechnungsPositionDO>("form") {
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
};
add(form);
csrfTokenHandler = new CsrfTokenHandler(form);
rows = new RepeatingView("rows");
form.add(rows);
}
/**
* @return the position
*/
public AbstractRechnungsPositionDO getPosition()
{
return position;
}
@SuppressWarnings("serial")
public RechnungCostEditTablePanel add(final AbstractRechnungsPositionDO origPosition)
{
if (origPosition instanceof RechnungsPositionDO) {
position = new RechnungsPositionDO();
} else {
position = new EingangsrechnungsPositionDO();
}
position.copyValuesFrom(origPosition, "kostZuweisungen");
new KostZuweisungenCopyHelper().mycopy(origPosition.getKostZuweisungen(), null, position);
List<KostZuweisungDO> kostzuweisungen = position.getKostZuweisungen();
if (CollectionUtils.isEmpty(kostzuweisungen) == true) {
addZuweisung(position);
kostzuweisungen = position.getKostZuweisungen();
}
for (final KostZuweisungDO zuweisung : kostzuweisungen) {
final WebMarkupContainer row = createRow(rows.newChildId(), position, zuweisung);
rows.add(row);
}
final Label restLabel = new Label("restValue", new Model<String>() {
/**
* @see org.apache.wicket.model.Model#getObject()
*/
@Override
public String getObject()
{
return CurrencyFormatter.format(position.getKostZuweisungNetFehlbetrag());
}
});
form.add(restLabel);
ajaxComponents.register(restLabel);
final AjaxButton addRowButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
final KostZuweisungDO zuweisung = addZuweisung(position);
final WebMarkupContainer newRow = createRow(rows.newChildId(), position, zuweisung);
newRow.setOutputMarkupId(true);
final StringBuffer prependJavascriptBuf = new StringBuffer();
prependJavascriptBuf.append(WicketAjaxUtils.appendChild("costAssignmentBody", "tr", newRow.getMarkupId()));
rows.add(newRow);
target.add(newRow);
ajaxComponents.addTargetComponents(target);
target.prependJavaScript(prependJavascriptBuf.toString());
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel);
}
};
// addRowButton.setDefaultFormProcessing(false);
final SingleButtonPanel addPositionButtonPanel = new SingleButtonPanel("addRowButton", addRowButton, getString("add"));
form.add(addPositionButtonPanel);
final AjaxButton recalculateButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
ajaxComponents.addTargetComponents(target);
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel);
}
};
// recalculateButton.setDefaultFormProcessing(false);
final SingleButtonPanel recalculateButtonPanel = new SingleButtonPanel("recalculateButton", recalculateButton, getString("recalculate"));
form.add(recalculateButtonPanel);
return this;
}
@SuppressWarnings("serial")
private WebMarkupContainer createRow(final String id, final AbstractRechnungsPositionDO position, final KostZuweisungDO zuweisung)
{
final WebMarkupContainer row = new WebMarkupContainer(id);
row.setOutputMarkupId(true);
final Kost1FormComponent kost1 = new Kost1FormComponent("kost1", new PropertyModel<Kost1DO>(zuweisung, "kost1"), true);
kost1.setLabel(new Model<String>(getString("fibu.kost1")));
row.add(kost1);
ajaxComponents.register(kost1);
final Kost2FormComponent kost2 = new Kost2FormComponent("kost2", new PropertyModel<Kost2DO>(zuweisung, "kost2"), true);
kost2.setLabel(new Model<String>(getString("fibu.kost2")));
row.add(kost2);
ajaxComponents.register(kost2);
final MinMaxNumberField<BigDecimal> netto = new MinMaxNumberField<BigDecimal>("netto",
new PropertyModel<BigDecimal>(zuweisung, "netto"), Constants.TEN_BILLION_NEGATIVE, Constants.TEN_BILLION) {
@SuppressWarnings({ "rawtypes", "unchecked"})
@Override
public IConverter getConverter(final Class type)
{
return new CurrencyConverter(position.getNetSum());
}
};
netto.setLabel(new Model<String>(getString("fibu.common.netto")));
WicketUtils.addTooltip(netto, getString("currencyConverter.percentage.help"));
row.add(netto);
ajaxComponents.register(netto); // Should be updated if e. g. percentage value is given.
final Label pLabel = new Label("percentage", new Model<String>() {
/**
* @see org.apache.wicket.model.Model#getObject()
*/
@Override
public String getObject()
{
final BigDecimal percentage;
if (NumberHelper.isZeroOrNull(position.getNetSum()) == true || NumberHelper.isZeroOrNull(zuweisung.getNetto()) == true) {
percentage = BigDecimal.ZERO;
} else {
percentage = zuweisung.getNetto().divide(position.getNetSum(), RoundingMode.HALF_UP);
}
final boolean percentageVisible = NumberHelper.isNotZero(percentage);
if (percentageVisible == true) {
return NumberFormatter.formatPercent(percentage);
} else {
return " ";
}
}
});
ajaxComponents.register(pLabel);
row.add(pLabel);
if (position.isKostZuweisungDeletable(zuweisung) == true) {
final AjaxButton deleteRowButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
position.deleteKostZuweisung(zuweisung.getIndex());
final StringBuffer prependJavascriptBuf = new StringBuffer();
prependJavascriptBuf.append(WicketAjaxUtils.removeChild("costAssignmentBody", row.getMarkupId()));
ajaxComponents.remove(row);
rows.remove(row);
target.prependJavaScript(prependJavascriptBuf.toString());
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel.setVisible(true));
}
};
deleteRowButton.setDefaultFormProcessing(false);
row.add(new IconButtonPanel("deleteEntry", deleteRowButton, IconType.TRASH, null).setLight());
} else {
// Don't show a delete button.
row.add(new Label("deleteEntry", " ").setEscapeModelStrings(false).setRenderBodyOnly(true));
}
return row;
}
private KostZuweisungDO addZuweisung(final AbstractRechnungsPositionDO position)
{
final KostZuweisungDO kostZuweisung = new KostZuweisungDO();
position.addKostZuweisung(kostZuweisung);
if (kostZuweisung.getIndex() > 0) {
final KostZuweisungDO predecessor = position.getKostZuweisung(kostZuweisung.getIndex() - 1);
if (predecessor != null) {
kostZuweisung.setKost1(predecessor.getKost1()); // Preset kost1 from the predecessor position.
kostZuweisung.setKost2(predecessor.getKost2()); // Preset kost2 from the predecessor position.
}
}
if (RechnungsPositionDO.class.isAssignableFrom(position.getClass()) == true && kostZuweisung.getKost2() == null) {
// Preset kost2 with first kost2 found for the projekt.
final RechnungsPositionDO rechnungsPosition = (RechnungsPositionDO) position;
if (rechnungsPosition != null) {
final RechnungDO rechnung = rechnungsPosition.getRechnung();
if (rechnung != null) {
final ProjektDO project = rechnung.getProjekt();
if (project != null) {
final List<Kost2DO> kost2List = kost2Dao.getActiveKost2(project);
if (CollectionUtils.isNotEmpty(kost2List) == true) {
kostZuweisung.setKost2(kost2List.get(0));
}
}
}
}
}
kostZuweisung.setNetto(position.getKostZuweisungNetFehlbetrag().negate());
return kostZuweisung;
}
/**
* @return the form
*/
public Form<AbstractRechnungsPositionDO> getForm()
{
return form;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_10 |
crossvul-java_data_bad_510_0 | /*
* Copyright 2016 http://www.hswebframework.org
*
* 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 org.hswebframework.web.oauth2.core;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public enum ErrorType {
ILLEGAL_CODE(1001), //错误的授权码
ILLEGAL_ACCESS_TOKEN(1002), //错误的access_token
ILLEGAL_CLIENT_ID(1003),//客户端信息错误
ILLEGAL_CLIENT_SECRET(1004),//客户端密钥错误
ILLEGAL_GRANT_TYPE(1005), //错误的授权方式
ILLEGAL_RESPONSE_TYPE(1006),//response_type 错误
ILLEGAL_AUTHORIZATION(1007),//Authorization 错误
ILLEGAL_REFRESH_TOKEN(1008),//refresh_token 错误
ILLEGAL_REDIRECT_URI(1009), //redirect_url 错误
ILLEGAL_SCOPE(1010), //scope 错误
ILLEGAL_USERNAME(1011), //username 错误
ILLEGAL_PASSWORD(1012), //password 错误
SCOPE_OUT_OF_RANGE(2010), //scope超出范围
UNAUTHORIZED_CLIENT(4010), //无权限
EXPIRED_TOKEN(4011), //TOKEN过期
INVALID_TOKEN(4012), //TOKEN已失效
UNSUPPORTED_GRANT_TYPE(4013), //不支持的认证类型
UNSUPPORTED_RESPONSE_TYPE(4014), //不支持的响应类型
EXPIRED_CODE(4015), //AUTHORIZATION_CODE过期
EXPIRED_REFRESH_TOKEN(4020), //REFRESH_TOKEN过期
CLIENT_DISABLED(4016),//客户端已被禁用
CLIENT_NOT_EXIST(4040),//客户端不存在
USER_NOT_EXIST(4041),//客户端不存在
ACCESS_DENIED(503), //访问被拒绝
OTHER(5001), //其他错误 ;
PARSE_RESPONSE_ERROR(5002),//解析返回结果错误
SERVICE_ERROR(5003); //服务器返回错误信息
private final String message;
private final int code;
static final Map<Integer, ErrorType> codeMapping = Arrays.stream(ErrorType.values())
.collect(Collectors.toMap(ErrorType::code, type -> type));
ErrorType(int code) {
this.code = code;
message = this.name().toLowerCase();
}
ErrorType(int code, String message) {
this.message = message;
this.code = code;
}
public String message() {
if (message == null) {
return this.name();
}
return message;
}
public int code() {
return code;
}
public <T> T throwThis(Function<ErrorType, ? extends RuntimeException> errorTypeFunction) {
throw errorTypeFunction.apply(this);
}
public <T> T throwThis(BiFunction<ErrorType, String, ? extends RuntimeException> errorTypeFunction, String message) {
throw errorTypeFunction.apply(this, message);
}
public static Optional<ErrorType> fromCode(int code) {
return Optional.ofNullable(codeMapping.get(code));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_510_0 |
crossvul-java_data_bad_2031_2 | package org.jolokia.http;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.management.*;
import org.jolokia.backend.BackendManager;
import org.jolokia.config.*;
import org.jolokia.request.JmxRequest;
import org.jolokia.request.JmxRequestFactory;
import org.jolokia.util.LogHandler;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Request handler with no dependency on the servlet API so that it can be used in
* several different environments (like for the Sun JDK 6 {@link com.sun.net.httpserver.HttpServer}.
*
* @author roland
* @since Mar 3, 2010
*/
public class HttpRequestHandler {
// handler for contacting the MBean server(s)
private BackendManager backendManager;
// Logging abstraction
private LogHandler logHandler;
// Global configuration
private Configuration config;
/**
* Request handler for parsing HTTP request and dispatching to the appropriate
* request handler (with help of the backend manager)
*
* @param pBackendManager backend manager to user
* @param pLogHandler log handler to where to put out logging
*/
public HttpRequestHandler(Configuration pConfig, BackendManager pBackendManager, LogHandler pLogHandler) {
backendManager = pBackendManager;
logHandler = pLogHandler;
config = pConfig;
}
/**
* Handle a GET request
*
* @param pUri URI leading to this request
* @param pPathInfo path of the request
* @param pParameterMap parameters of the GET request @return the response
*/
public JSONAware handleGetRequest(String pUri, String pPathInfo, Map<String, String[]> pParameterMap) {
String pathInfo = extractPathInfo(pUri, pPathInfo);
JmxRequest jmxReq =
JmxRequestFactory.createGetRequest(pathInfo,getProcessingParameter(pParameterMap));
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
logHandler.debug("Path-Info: " + pathInfo);
logHandler.debug("Request: " + jmxReq.toString());
}
return executeRequest(jmxReq);
}
private ProcessingParameters getProcessingParameter(Map<String, String[]> pParameterMap) {
Map<String,String> ret = new HashMap<String, String>();
if (pParameterMap != null) {
for (Map.Entry<String,String[]> entry : pParameterMap.entrySet()) {
String values[] = entry.getValue();
if (values != null && values.length > 0) {
ret.put(entry.getKey(), values[0]);
}
}
}
return config.getProcessingParameters(ret);
}
/**
* Handle the input stream as given by a POST request
*
*
* @param pUri URI leading to this request
* @param pInputStream input stream of the post request
* @param pEncoding optional encoding for the stream. If null, the default encoding is used
* @param pParameterMap additional processing parameters
* @return the JSON object containing the json results for one or more {@link JmxRequest} contained
* within the answer.
*
* @throws IOException if reading from the input stream fails
*/
public JSONAware handlePostRequest(String pUri, InputStream pInputStream, String pEncoding, Map<String, String[]> pParameterMap)
throws IOException {
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
}
Object jsonRequest = extractJsonRequest(pInputStream,pEncoding);
if (jsonRequest instanceof JSONArray) {
List<JmxRequest> jmxRequests = JmxRequestFactory.createPostRequests((List) jsonRequest,getProcessingParameter(pParameterMap));
JSONArray responseList = new JSONArray();
for (JmxRequest jmxReq : jmxRequests) {
if (backendManager.isDebug()) {
logHandler.debug("Request: " + jmxReq.toString());
}
// Call handler and retrieve return value
JSONObject resp = executeRequest(jmxReq);
responseList.add(resp);
}
return responseList;
} else if (jsonRequest instanceof JSONObject) {
JmxRequest jmxReq = JmxRequestFactory.createPostRequest((Map<String, ?>) jsonRequest,getProcessingParameter(pParameterMap));
return executeRequest(jmxReq);
} else {
throw new IllegalArgumentException("Invalid JSON Request " + jsonRequest);
}
}
/**
* Handling an option request which is used for preflight checks before a CORS based browser request is
* sent (for certain circumstances).
*
* See the <a href="http://www.w3.org/TR/cors/">CORS specification</a>
* (section 'preflight checks') for more details.
*
* @param pOrigin the origin to check. If <code>null</code>, no headers are returned
* @param pRequestHeaders extra headers to check against
* @return headers to set
*/
public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
Map<String,String> ret = new HashMap<String, String>();
if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {
// CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
if (pRequestHeaders != null) {
ret.put("Access-Control-Allow-Headers",pRequestHeaders);
}
// Fix for CORS with authentication (#104)
ret.put("Access-Control-Allow-Credentials","true");
// Allow for one year. Changes in access.xml are reflected directly in the cors request itself
ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
}
return ret;
}
private Object extractJsonRequest(InputStream pInputStream, String pEncoding) throws IOException {
InputStreamReader reader = null;
try {
reader =
pEncoding != null ?
new InputStreamReader(pInputStream, pEncoding) :
new InputStreamReader(pInputStream);
JSONParser parser = new JSONParser();
return parser.parse(reader);
} catch (ParseException exp) {
throw new IllegalArgumentException("Invalid JSON request " + reader,exp);
}
}
/**
* Execute a single {@link JmxRequest}. If a checked exception occurs,
* this gets translated into the appropriate JSON object which will get returned.
* Note, that these exceptions gets *not* translated into an HTTP error, since they are
* supposed <em>Jolokia</em> specific errors above the transport layer.
*
* @param pJmxReq the request to execute
* @return the JSON representation of the answer.
*/
private JSONObject executeRequest(JmxRequest pJmxReq) {
// Call handler and retrieve return value
try {
return backendManager.handleRequest(pJmxReq);
} catch (ReflectionException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (InstanceNotFoundException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (MBeanException e) {
return getErrorJSON(500,e.getTargetException(), pJmxReq);
} catch (AttributeNotFoundException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (UnsupportedOperationException e) {
return getErrorJSON(500,e, pJmxReq);
} catch (IOException e) {
return getErrorJSON(500,e, pJmxReq);
} catch (IllegalArgumentException e) {
return getErrorJSON(400,e, pJmxReq);
} catch (SecurityException e) {
// Wipe out stacktrace
return getErrorJSON(403,new Exception(e.getMessage()), pJmxReq);
} catch (RuntimeMBeanException e) {
// Use wrapped exception
return errorForUnwrappedException(e,pJmxReq);
}
}
/**
* Utility method for handling single runtime exceptions and errors. This method is called
* in addition to and after {@link #executeRequest(JmxRequest)} to catch additional errors.
* They are two different methods because of bulk requests, where each individual request can
* lead to an error. So, each individual request is wrapped with the error handling of
* {@link #executeRequest(JmxRequest)}
* whereas the overall handling is wrapped with this method. It is hence more coarse grained,
* leading typically to an status code of 500.
*
* Summary: This method should be used as last security belt is some exception should escape
* from a single request processing in {@link #executeRequest(JmxRequest)}.
*
* @param pThrowable exception to handle
* @return its JSON representation
*/
public JSONObject handleThrowable(Throwable pThrowable) {
if (pThrowable instanceof IllegalArgumentException) {
return getErrorJSON(400,pThrowable, null);
} else if (pThrowable instanceof SecurityException) {
// Wipe out stacktrace
return getErrorJSON(403,new Exception(pThrowable.getMessage()), null);
} else {
return getErrorJSON(500,pThrowable, null);
}
}
/**
* Get the JSON representation for a an exception
*
*
* @param pErrorCode the HTTP error code to return
* @param pExp the exception or error occured
* @param pJmxReq request from where to get processing options
* @return the json representation
*/
public JSONObject getErrorJSON(int pErrorCode, Throwable pExp, JmxRequest pJmxReq) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status",pErrorCode);
jsonObject.put("error",getExceptionMessage(pExp));
jsonObject.put("error_type", pExp.getClass().getName());
addErrorInfo(jsonObject, pExp, pJmxReq);
if (backendManager.isDebug()) {
backendManager.error("Error " + pErrorCode,pExp);
}
if (pJmxReq != null) {
jsonObject.put("request",pJmxReq.toJSON());
}
return jsonObject;
}
/**
* Check whether the given host and/or address is allowed to access this agent.
*
* @param pHost host to check
* @param pAddress address to check
*/
public void checkClientIPAccess(String pHost, String pAddress) {
if (!backendManager.isRemoteAccessAllowed(pHost,pAddress)) {
throw new SecurityException("No access from client " + pAddress + " allowed");
}
}
/**
* Check whether for the given host is a cross-browser request allowed. This check is deligated to the
* backendmanager which is responsible for the security configuration.
* Also, some sanity checks are applied.
*
* @param pOrigin the origin URL to check against
* @return the origin to put in the response header or null if none is to be set
*/
public String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isCorsAccessAllowed(origin)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
}
private void addErrorInfo(JSONObject pErrorResp, Throwable pExp, JmxRequest pJmxReq) {
String includeStackTrace = pJmxReq != null ?
pJmxReq.getParameter(ConfigKey.INCLUDE_STACKTRACE) : "true";
if (includeStackTrace.equalsIgnoreCase("true") ||
(includeStackTrace.equalsIgnoreCase("runtime") && pExp instanceof RuntimeException)) {
StringWriter writer = new StringWriter();
pExp.printStackTrace(new PrintWriter(writer));
pErrorResp.put("stacktrace",writer.toString());
}
if (pJmxReq != null && pJmxReq.getParameterAsBool(ConfigKey.SERIALIZE_EXCEPTION)) {
pErrorResp.put("error_value",backendManager.convertExceptionToJson(pExp,pJmxReq));
}
}
// Extract class and exception message for an error message
private String getExceptionMessage(Throwable pException) {
String message = pException.getLocalizedMessage();
return pException.getClass().getName() + (message != null ? " : " + message : "");
}
// Unwrap an exception to get to the 'real' exception
// and extract the error code accordingly
private JSONObject errorForUnwrappedException(Exception e, JmxRequest pJmxReq) {
Throwable cause = e.getCause();
int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500;
return getErrorJSON(code,cause, pJmxReq);
}
// Path info might need some special handling in case when the URL
// contains two following slashes. These slashes get collapsed
// when calling getPathInfo() but are still present in the URI.
// This situation can happen, when slashes are escaped and the last char
// of an path part is such an escaped slash
// (e.g. "read/domain:type=name!//attribute")
// In this case, we extract the path info on our own
private static final Pattern PATH_PREFIX_PATTERN = Pattern.compile("^/?[^/]+/");
private String extractPathInfo(String pUri, String pPathInfo) {
if (pUri.contains("!//")) {
// Special treatment for trailing slashes in paths
Matcher matcher = PATH_PREFIX_PATTERN.matcher(pPathInfo);
if (matcher.find()) {
String prefix = matcher.group();
String pathInfoEncoded = pUri.replaceFirst("^.*?" + prefix, prefix);
try {
return URLDecoder.decode(pathInfoEncoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Should not happen at all ... so we silently fall through
}
}
}
return pPathInfo;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_2 |
crossvul-java_data_good_2031_3 | package org.jolokia.restrictor;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
/**
* Base restrictor which alway returns the constant given
* at construction time
*
* @author roland
* @since 06.10.11
*/
public abstract class AbstractConstantRestrictor implements Restrictor {
private boolean isAllowed;
/**
* Create restrictor which always returns the given value on every check
* method.
*
* @param pAllowed whether access is allowed or denied
*/
protected AbstractConstantRestrictor(boolean pAllowed) {
isAllowed = pAllowed;
}
/** {@inheritDoc} */
public final boolean isHttpMethodAllowed(HttpMethod pMethod) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isTypeAllowed(RequestType pType) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isOperationAllowed(ObjectName pName, String pOperation) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isRemoteAccessAllowed(String... pHostOrAddress) {
return isAllowed;
}
/** {@inheritDoc} */
public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
return isAllowed;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_3 |
crossvul-java_data_bad_2028_4 | package io.hawt.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Principal;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import io.hawt.system.ConfigManager;
import io.hawt.system.Helpers;
import org.jolokia.converter.Converters;
import org.jolokia.converter.json.JsonConvertOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final transient Logger LOG = LoggerFactory.getLogger(LoginServlet.class);
Converters converters = new Converters();
JsonConvertOptions options = JsonConvertOptions.DEFAULT;
ConfigManager config;
private Integer timeout;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
config = (ConfigManager) servletConfig.getServletContext().getAttribute("ConfigManager");
if (config != null) {
String s = config.get("sessionTimeout", null);
if (s != null) {
try {
timeout = Integer.parseInt(s);
// timeout of 0 means default timeout
if (timeout == 0) {
timeout = null;
}
} catch (Exception e) {
// ignore and use default timeout value
}
}
}
LOG.info("hawtio login is using " + (timeout != null ? timeout + " sec." : "default") + " HttpSession timeout");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
final PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(false);
if (session != null) {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
LOG.warn("No security subject stored in existing session, invalidating");
session.invalidate();
Helpers.doForbidden(resp);
}
returnPrincipals(subject, out);
return;
}
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(resp);
return;
}
Set<Principal> principals = subject.getPrincipals();
String username = null;
if (principals != null) {
for (Principal principal : principals) {
if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
username = principal.getName();
LOG.debug("Authorizing user {}", username);
}
}
}
session = req.getSession(true);
session.setAttribute("subject", subject);
session.setAttribute("user", username);
session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
if (timeout != null) {
session.setMaxInactiveInterval(timeout);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
}
returnPrincipals(subject, out);
}
private void returnPrincipals(Subject subject, PrintWriter out) {
Map<String, Object> answer = new HashMap<String, Object>();
List<Object> principals = new ArrayList<Object>();
for (Principal principal : subject.getPrincipals()) {
Map<String, String> data = new HashMap<String, String>();
data.put("type", principal.getClass().getName());
data.put("name", principal.getName());
principals.add(data);
}
List<Object> credentials = new ArrayList<Object>();
for (Object credential : subject.getPublicCredentials()) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", credential.getClass().getName());
data.put("credential", credential);
}
answer.put("principals", principals);
answer.put("credentials", credentials);
ServletHelpers.writeObject(converters, options, out, answer);
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2028_4 |
crossvul-java_data_bad_3058_0 | /*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
* Tom Huybrechts, Vincent Latombe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.google.common.base.Predicate;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.*;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.SecurityRealm;
import hudson.security.UserMayOrMayNotExistException;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.RunList;
import hudson.util.XStream2;
import jenkins.model.IdStrategy;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithContextMenu;
import jenkins.security.ImpersonatingUserDetailsService;
import jenkins.security.LastGrantedAuthoritiesProperty;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Represents a user.
*
* <p>
* In Hudson, {@link User} objects are created in on-demand basis;
* for example, when a build is performed, its change log is computed
* and as a result commits from users who Hudson has never seen may be discovered.
* When this happens, new {@link User} object is created.
*
* <p>
* If the persisted record for an user exists, the information is loaded at
* that point, but if there's no such record, a fresh instance is created from
* thin air (this is where {@link UserPropertyDescriptor#newInstance(User)} is
* called to provide initial {@link UserProperty} objects.
*
* <p>
* Such newly created {@link User} objects will be simply GC-ed without
* ever leaving the persisted record, unless {@link User#save()} method
* is explicitly invoked (perhaps as a result of a browser submitting a
* configuration.)
*
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class User extends AbstractModelObject implements AccessControlled, DescriptorByNameOwner, Saveable, Comparable<User>, ModelObjectWithContextMenu {
/**
* The username of the 'unknown' user used to avoid null user references.
*/
private static final String UKNOWN_USERNAME = "unknown";
/**
* These usernames should not be used by real users logging into Jenkins. Therefore, we prevent
* users with these names from being saved.
*/
private static final String[] ILLEGAL_PERSISTED_USERNAMES = new String[]{ACL.ANONYMOUS_USERNAME,
ACL.SYSTEM_USERNAME, UKNOWN_USERNAME};
private transient final String id;
private volatile String fullName;
private volatile String description;
/**
* List of {@link UserProperty}s configured for this project.
*/
@CopyOnWrite
private volatile List<UserProperty> properties = new ArrayList<UserProperty>();
private User(String id, String fullName) {
this.id = id;
this.fullName = fullName;
load();
}
/**
* Returns the {@link jenkins.model.IdStrategy} for use with {@link User} instances. See
* {@link hudson.security.SecurityRealm#getUserIdStrategy()}
*
* @return the {@link jenkins.model.IdStrategy} for use with {@link User} instances.
* @since 1.566
*/
@Nonnull
public static IdStrategy idStrategy() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return IdStrategy.CASE_INSENSITIVE;
}
SecurityRealm realm = j.getSecurityRealm();
if (realm == null) {
return IdStrategy.CASE_INSENSITIVE;
}
return realm.getUserIdStrategy();
}
public int compareTo(User that) {
return idStrategy().compare(this.id, that.id);
}
/**
* Loads the other data from disk if it's available.
*/
private synchronized void load() {
properties.clear();
XmlFile config = getConfigFile();
try {
if(config.exists())
config.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
}
// remove nulls that have failed to load
for (Iterator<UserProperty> itr = properties.iterator(); itr.hasNext();) {
if(itr.next()==null)
itr.remove();
}
// allocate default instances if needed.
// doing so after load makes sure that newly added user properties do get reflected
for (UserPropertyDescriptor d : UserProperty.all()) {
if(getProperty(d.clazz)==null) {
UserProperty up = d.newInstance(this);
if(up!=null)
properties.add(up);
}
}
for (UserProperty p : properties)
p.setUser(this);
}
@Exported
public String getId() {
return id;
}
public @Nonnull String getUrl() {
return "user/"+Util.rawEncode(idStrategy().keyFor(id));
}
public @Nonnull String getSearchUrl() {
return "/user/"+Util.rawEncode(idStrategy().keyFor(id));
}
/**
* The URL of the user page.
*/
@Exported(visibility=999)
public @Nonnull String getAbsoluteUrl() {
return Jenkins.getInstance().getRootUrl()+getUrl();
}
/**
* Gets the human readable name of this user.
* This is configurable by the user.
*/
@Exported(visibility=999)
public @Nonnull String getFullName() {
return fullName;
}
/**
* Sets the human readable name of the user.
* If the input parameter is empty, the user's ID will be set.
*/
public void setFullName(String name) {
if(Util.fixEmptyAndTrim(name)==null) name=id;
this.fullName = name;
}
@Exported
public @CheckForNull String getDescription() {
return description;
}
/**
* Sets the description of the user.
* @since 1.609
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the user properties configured for this user.
*/
public Map<Descriptor<UserProperty>,UserProperty> getProperties() {
return Descriptor.toMap(properties);
}
/**
* Updates the user object by adding a property.
*/
public synchronized void addProperty(@Nonnull UserProperty p) throws IOException {
UserProperty old = getProperty(p.getClass());
List<UserProperty> ps = new ArrayList<UserProperty>(properties);
if(old!=null)
ps.remove(old);
ps.add(p);
p.setUser(this);
properties = ps;
save();
}
/**
* List of all {@link UserProperty}s exposed primarily for the remoting API.
*/
@Exported(name="property",inline=true)
public List<UserProperty> getAllProperties() {
return Collections.unmodifiableList(properties);
}
/**
* Gets the specific property, or null.
*/
public <T extends UserProperty> T getProperty(Class<T> clazz) {
for (UserProperty p : properties) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
/**
* Creates an {@link Authentication} object that represents this user.
*
* This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
* If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
* use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
* logged in.
*
* @throws UsernameNotFoundException
* If this user is not a valid user in the backend {@link SecurityRealm}.
* @since 1.419
*/
public @Nonnull Authentication impersonate() throws UsernameNotFoundException {
try {
UserDetails u = new ImpersonatingUserDetailsService(
Jenkins.getInstance().getSecurityRealm().getSecurityComponents().userDetails).loadUserByUsername(id);
return new UsernamePasswordAuthenticationToken(u.getUsername(), "", u.getAuthorities());
} catch (UserMayOrMayNotExistException e) {
// backend can't load information about other users. so use the stored information if available
} catch (UsernameNotFoundException e) {
// if the user no longer exists in the backend, we need to refuse impersonating this user
if (!ALLOW_NON_EXISTENT_USER_TO_LOGIN)
throw e;
} catch (DataAccessException e) {
// seems like it's in the same boat as UserMayOrMayNotExistException
}
// seems like a legitimate user we have no idea about. proceed with minimum access
return new UsernamePasswordAuthenticationToken(id, "",
new GrantedAuthority[]{SecurityRealm.AUTHENTICATED_AUTHORITY});
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
description = req.getParameter("description");
save();
rsp.sendRedirect("."); // go to the top page
}
/**
* Gets the fallback "unknown" user instance.
* <p>
* This is used to avoid null {@link User} instance.
*/
public static @Nonnull User getUnknown() {
return getById(UKNOWN_USERNAME, true);
}
/**
* Gets the {@link User} object by its id or full name.
*
* @param create
* If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
* @return Requested user. May be {@code null} if a user does not exist and
* {@code create} is false.
* @deprecated use {@link User#get(String, boolean, java.util.Map)}
*/
@Deprecated
public static @Nullable User get(String idOrFullName, boolean create) {
return get(idOrFullName, create, Collections.emptyMap());
}
/**
* Gets the {@link User} object by its id or full name.
*
* @param create
* If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
*
* @param context
* contextual environment this user idOfFullName was retrieved from,
* that can help resolve the user ID
*
* @return
* An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
public static @Nullable User get(String idOrFullName, boolean create, Map context) {
if(idOrFullName==null)
return null;
// sort resolvers by priority
List<CanonicalIdResolver> resolvers = new ArrayList<CanonicalIdResolver>(ExtensionList.lookup(CanonicalIdResolver.class));
Collections.sort(resolvers);
String id = null;
for (CanonicalIdResolver resolver : resolvers) {
id = resolver.resolveCanonicalId(idOrFullName, context);
if (id != null) {
LOGGER.log(Level.FINE, "{0} mapped {1} to {2}", new Object[] {resolver, idOrFullName, id});
break;
}
}
// DefaultUserCanonicalIdResolver will always return a non-null id if all other CanonicalIdResolver failed
if (id == null) {
throw new IllegalStateException("The user id should be always non-null thanks to DefaultUserCanonicalIdResolver");
}
return getOrCreate(id, idOrFullName, create);
}
/**
* Retrieve a user by its ID, and create a new one if requested.
* @return
* An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
private static @Nullable User getOrCreate(@Nonnull String id, @Nonnull String fullName, boolean create) {
String idkey = idStrategy().keyFor(id);
byNameLock.readLock().lock();
User u;
try {
u = byName.get(idkey);
} finally {
byNameLock.readLock().unlock();
}
final File configFile = getConfigFileFor(id);
if (!configFile.isFile() && !configFile.getParentFile().isDirectory()) {
// check for legacy users and migrate if safe to do so.
File[] legacy = getLegacyConfigFilesFor(id);
if (legacy != null && legacy.length > 0) {
for (File legacyUserDir : legacy) {
final XmlFile legacyXml = new XmlFile(XSTREAM, new File(legacyUserDir, "config.xml"));
try {
Object o = legacyXml.read();
if (o instanceof User) {
if (idStrategy().equals(id, legacyUserDir.getName()) && !idStrategy().filenameOf(legacyUserDir.getName())
.equals(legacyUserDir.getName())) {
if (!legacyUserDir.renameTo(configFile.getParentFile())) {
LOGGER.log(Level.WARNING, "Failed to migrate user record from {0} to {1}",
new Object[]{legacyUserDir, configFile.getParentFile()});
}
break;
}
} else {
LOGGER.log(Level.FINE, "Unexpected object loaded from {0}: {1}",
new Object[]{ legacyUserDir, o });
}
} catch (IOException e) {
LOGGER.log(Level.FINE, String.format("Exception trying to load user from {0}: {1}",
new Object[]{ legacyUserDir, e.getMessage() }), e);
}
}
}
}
if (u==null && (create || configFile.exists())) {
User tmp = new User(id, fullName);
User prev;
byNameLock.readLock().lock();
try {
prev = byName.putIfAbsent(idkey, u = tmp);
} finally {
byNameLock.readLock().unlock();
}
if (prev != null) {
u = prev; // if some has already put a value in the map, use it
if (LOGGER.isLoggable(Level.FINE) && !fullName.equals(prev.getFullName())) {
LOGGER.log(Level.FINE, "mismatch on fullName (‘" + fullName + "’ vs. ‘" + prev.getFullName() + "’) for ‘" + id + "’", new Throwable());
}
} else if (!id.equals(fullName) && !configFile.exists()) {
// JENKINS-16332: since the fullName may not be recoverable from the id, and various code may store the id only, we must save the fullName
try {
u.save();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}
return u;
}
/**
* Gets the {@link User} object by its id or full name.
* Use {@link #getById} when you know you have an ID.
*/
public static @Nonnull User get(String idOrFullName) {
return get(idOrFullName,true);
}
/**
* Gets the {@link User} object representing the currently logged-in user, or null
* if the current user is anonymous.
* @since 1.172
*/
public static @CheckForNull User current() {
return get(Jenkins.getAuthentication());
}
/**
* Gets the {@link User} object representing the supplied {@link Authentication} or
* {@code null} if the supplied {@link Authentication} is either anonymous or {@code null}
* @param a the supplied {@link Authentication} .
* @return a {@link User} object for the supplied {@link Authentication} or {@code null}
* @since 1.609
*/
public static @CheckForNull User get(@CheckForNull Authentication a) {
if(a == null || a instanceof AnonymousAuthenticationToken)
return null;
// Since we already know this is a name, we can just call getOrCreate with the name directly.
String id = a.getName();
return getById(id, true);
}
/**
* Gets the {@link User} object by its <code>id</code>
*
* @param id
* the id of the user to retrieve and optionally create if it does not exist.
* @param create
* If <code>true</code>, this method will never return <code>null</code> for valid input (by creating a
* new {@link User} object if none exists.) If <code>false</code>, this method will return
* <code>null</code> if {@link User} object with the given id doesn't exist.
* @return the a User whose id is <code>id</code>, or <code>null</code> if <code>create</code> is <code>false</code>
* and the user does not exist.
*/
public static @Nullable User getById(String id, boolean create) {
return getOrCreate(id, id, create);
}
private static volatile long lastScanned;
/**
* Gets all the users.
*/
public static @Nonnull Collection<User> getAll() {
final IdStrategy strategy = idStrategy();
if(System.currentTimeMillis() -lastScanned>10000) {
// occasionally scan the file system to check new users
// whether we should do this only once at start up or not is debatable.
// set this right away to avoid another thread from doing the same thing while we do this.
// having two threads doing the work won't cause race condition, but it's waste of time.
lastScanned = System.currentTimeMillis();
File[] subdirs = getRootDir().listFiles((FileFilter)DirectoryFileFilter.INSTANCE);
if(subdirs==null) return Collections.emptyList(); // shall never happen
for (File subdir : subdirs)
if(new File(subdir,"config.xml").exists()) {
String name = strategy.idFromFilename(subdir.getName());
User.getOrCreate(name, name, true);
}
lastScanned = System.currentTimeMillis();
}
byNameLock.readLock().lock();
ArrayList<User> r;
try {
r = new ArrayList<User>(byName.values());
} finally {
byNameLock.readLock().unlock();
}
Collections.sort(r,new Comparator<User>() {
public int compare(User o1, User o2) {
return strategy.compare(o1.getId(), o2.getId());
}
});
return r;
}
/**
* Reloads the configuration from disk.
*/
public static void reload() {
byNameLock.readLock().lock();
try {
for (User u : byName.values()) {
u.load();
}
} finally {
byNameLock.readLock().unlock();
}
}
/**
* Stop gap hack. Don't use it. To be removed in the trunk.
*/
public static void clear() {
byNameLock.writeLock().lock();
try {
byName.clear();
} finally {
byNameLock.writeLock().unlock();
}
}
/**
* Called when changing the {@link IdStrategy}.
* @since 1.566
*/
public static void rekey() {
final IdStrategy strategy = idStrategy();
byNameLock.writeLock().lock();
try {
for (Map.Entry<String, User> e : byName.entrySet()) {
String idkey = strategy.keyFor(e.getValue().id);
if (!idkey.equals(e.getKey())) {
// need to remap
byName.remove(e.getKey());
byName.putIfAbsent(idkey, e.getValue());
}
}
} finally {
byNameLock.writeLock().unlock();
}
}
/**
* Returns the user name.
*/
public @Nonnull String getDisplayName() {
return getFullName();
}
/** true if {@link AbstractBuild#hasParticipant} or {@link hudson.model.Cause.UserIdCause} */
private boolean relatedTo(@Nonnull AbstractBuild<?,?> b) {
if (b.hasParticipant(this)) {
return true;
}
for (Cause cause : b.getCauses()) {
if (cause instanceof Cause.UserIdCause) {
String userId = ((Cause.UserIdCause) cause).getUserId();
if (userId != null && idStrategy().equals(userId, getId())) {
return true;
}
}
}
return false;
}
/**
* Gets the list of {@link Build}s that include changes by this user,
* by the timestamp order.
*/
@WithBridgeMethods(List.class)
public @Nonnull RunList getBuilds() {
return new RunList<Run<?,?>>(Jenkins.getInstance().getAllItems(Job.class)).filter(new Predicate<Run<?,?>>() {
@Override public boolean apply(Run<?,?> r) {
return r instanceof AbstractBuild && relatedTo((AbstractBuild<?,?>) r);
}
});
}
/**
* Gets all the {@link AbstractProject}s that this user has committed to.
* @since 1.191
*/
public @Nonnull Set<AbstractProject<?,?>> getProjects() {
Set<AbstractProject<?,?>> r = new HashSet<AbstractProject<?,?>>();
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class))
if(p.hasParticipant(this))
r.add(p);
return r;
}
public @Override String toString() {
return fullName;
}
/**
* The file we save our configuration.
*/
protected final XmlFile getConfigFile() {
return new XmlFile(XSTREAM,getConfigFileFor(id));
}
private static final File getConfigFileFor(String id) {
return new File(getRootDir(), idStrategy().filenameOf(id) +"/config.xml");
}
private static final File[] getLegacyConfigFilesFor(final String id) {
return getRootDir().listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() && new File(pathname, "config.xml").isFile() && idStrategy().equals(
pathname.getName(), id);
}
});
}
/**
* Gets the directory where Hudson stores user information.
*/
private static File getRootDir() {
return new File(Jenkins.getInstance().getRootDir(), "users");
}
/**
* Is the ID allowed? Some are prohibited for security reasons. See SECURITY-166.
* <p/>
* Note that this is only enforced when saving. These users are often created
* via the constructor (and even listed on /asynchPeople), but our goal is to
* prevent anyone from logging in as these users. Therefore, we prevent
* saving a User with one of these ids.
*
* @return true if the username or fullname is valid
* @since 1.600
*/
public static boolean isIdOrFullnameAllowed(String id) {
for (String invalidId : ILLEGAL_PERSISTED_USERNAMES) {
if (id.equalsIgnoreCase(invalidId))
return false;
}
return true;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException, FormValidation {
if (! isIdOrFullnameAllowed(id)) {
throw FormValidation.error(Messages.User_IllegalUsername(id));
}
if (! isIdOrFullnameAllowed(fullName)) {
throw FormValidation.error(Messages.User_IllegalFullname(fullName));
}
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Deletes the data directory and removes this user from Hudson.
*
* @throws IOException
* if we fail to delete.
*/
public synchronized void delete() throws IOException {
final IdStrategy strategy = idStrategy();
byNameLock.readLock().lock();
try {
byName.remove(strategy.keyFor(id));
} finally {
byNameLock.readLock().unlock();
}
Util.deleteRecursive(new File(getRootDir(), strategy.filenameOf(id)));
}
/**
* Exposed remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Accepts submission from the configuration page.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(Jenkins.ADMINISTER);
JSONObject json = req.getSubmittedForm();
fullName = json.getString("fullName");
description = json.getString("description");
List<UserProperty> props = new ArrayList<UserProperty>();
int i = 0;
for (UserPropertyDescriptor d : UserProperty.all()) {
UserProperty p = getProperty(d.clazz);
JSONObject o = json.optJSONObject("userProperty" + (i++));
if (o!=null) {
if (p != null) {
p = p.reconfigure(req, o);
} else {
p = d.newInstance(req, o);
}
p.setUser(this);
}
if (p!=null)
props.add(p);
}
this.properties = props;
save();
FormApply.success(".").generateResponse(req,rsp,this);
}
/**
* Deletes this user from Hudson.
*/
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
if (idStrategy().equals(id, Jenkins.getAuthentication().getName())) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot delete self");
return;
}
delete();
rsp.sendRedirect2("../..");
}
public void doRssAll(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds(), Run.FEED_ADAPTER);
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
rss(req, rsp, " regression builds", getBuilds().regressionOnly(), Run.FEED_ADAPTER);
}
public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
final List<Run> lastBuilds = new ArrayList<Run>();
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
for (AbstractBuild<?,?> b = p.getLastBuild(); b != null; b = b.getPreviousBuild()) {
if (relatedTo(b)) {
lastBuilds.add(b);
break;
}
}
}
rss(req, rsp, " latest build", RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST);
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs, FeedAdapter adapter)
throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(), runs.newBuilds(), adapter, req, rsp);
}
/**
* Keyed by {@link User#id}. This map is used to ensure
* singleton-per-id semantics of {@link User} objects.
*
* The key needs to be generated by {@link IdStrategy#keyFor(String)}.
*/
@GuardedBy("byNameLock")
private static final ConcurrentMap<String,User> byName = new ConcurrentHashMap<String, User>();
/**
* This lock is used to guard access to the {@link #byName} map. Use
* {@link java.util.concurrent.locks.ReadWriteLock#readLock()} for normal access and
* {@link java.util.concurrent.locks.ReadWriteLock#writeLock()} for {@link #rekey()} or any other operation
* that requires operating on the map as a whole.
*/
private static final ReadWriteLock byNameLock = new ReentrantReadWriteLock();
/**
* Used to load/save user configuration.
*/
public static final XStream2 XSTREAM = new XStream2();
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
static {
XSTREAM.alias("user",User.class);
}
public ACL getACL() {
final ACL base = Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
// always allow a non-anonymous user full control of himself.
return new ACL() {
public boolean hasPermission(Authentication a, Permission permission) {
return (idStrategy().equals(a.getName(), id) && !(a instanceof AnonymousAuthenticationToken))
|| base.hasPermission(a, permission);
}
};
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* With ADMINISTER permission, can delete users with persisted data but can't delete self.
*/
public boolean canDelete() {
final IdStrategy strategy = idStrategy();
return hasPermission(Jenkins.ADMINISTER) && !strategy.equals(id, Jenkins.getAuthentication().getName())
&& new File(getRootDir(), strategy.filenameOf(id)).exists();
}
/**
* Checks for authorities (groups) associated with this user.
* If the caller lacks {@link Jenkins#ADMINISTER}, or any problems arise, returns an empty list.
* {@link SecurityRealm#AUTHENTICATED_AUTHORITY} and the username, if present, are omitted.
* @since 1.498
* @return a possibly empty list
*/
public @Nonnull List<String> getAuthorities() {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return Collections.emptyList();
}
List<String> r = new ArrayList<String>();
Authentication authentication;
try {
authentication = impersonate();
} catch (UsernameNotFoundException x) {
LOGGER.log(Level.FINE, "cannot look up authorities for " + id, x);
return Collections.emptyList();
}
for (GrantedAuthority a : authentication.getAuthorities()) {
if (a.equals(SecurityRealm.AUTHENTICATED_AUTHORITY)) {
continue;
}
String n = a.getAuthority();
if (n != null && !idStrategy().equals(n, id)) {
r.add(n);
}
}
Collections.sort(r, String.CASE_INSENSITIVE_ORDER);
return r;
}
public Descriptor getDescriptorByName(String className) {
return Jenkins.getInstance().getDescriptorByName(className);
}
public Object getDynamic(String token) {
for(Action action: getTransientActions()){
if(action.getUrlName().equals(token))
return action;
}
for(Action action: getPropertyActions()){
if(action.getUrlName().equals(token))
return action;
}
return null;
}
/**
* Return all properties that are also actions.
*
* @return the list can be empty but never null. read only.
*/
public List<Action> getPropertyActions() {
List<Action> actions = new ArrayList<Action>();
for (UserProperty userProp : getProperties().values()) {
if (userProp instanceof Action) {
actions.add((Action) userProp);
}
}
return Collections.unmodifiableList(actions);
}
/**
* Return all transient actions associated with this user.
*
* @return the list can be empty but never null. read only.
*/
public List<Action> getTransientActions() {
List<Action> actions = new ArrayList<Action>();
for (TransientUserActionFactory factory: TransientUserActionFactory.all()) {
actions.addAll(factory.createFor(this));
}
return Collections.unmodifiableList(actions);
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
return new ContextMenu().from(this,request,response);
}
public static abstract class CanonicalIdResolver extends AbstractDescribableImpl<CanonicalIdResolver> implements ExtensionPoint, Comparable<CanonicalIdResolver> {
/**
* context key for realm (domain) where idOrFullName has been retreived from.
* Can be used (for example) to distinguish ambiguous committer ID using the SCM URL.
* Associated Value is a {@link String}
*/
public static final String REALM = "realm";
public int compareTo(CanonicalIdResolver o) {
// reverse priority order
int i = getPriority();
int j = o.getPriority();
return i>j ? -1 : (i==j ? 0:1);
}
/**
* extract user ID from idOrFullName with help from contextual infos.
* can return <code>null</code> if no user ID matched the input
*/
public abstract @CheckForNull String resolveCanonicalId(String idOrFullName, Map<String, ?> context);
public int getPriority() {
return 1;
}
}
/**
* Resolve user ID from full name
*/
@Extension
public static class FullNameIdResolver extends CanonicalIdResolver {
@Override
public String resolveCanonicalId(String idOrFullName, Map<String, ?> context) {
for (User user : getAll()) {
if (idOrFullName.equals(user.getFullName())) return user.getId();
}
return null;
}
@Override
public int getPriority() {
return -1; // lower than default
}
}
/**
* Tries to verify if an ID is valid.
* If so, we do not want to even consider users who might have the same full name.
*/
@Extension
@Restricted(NoExternalUse.class)
public static class UserIDCanonicalIdResolver extends User.CanonicalIdResolver {
private static /* not final */ boolean SECURITY_243_FULL_DEFENSE = Boolean.parseBoolean(System.getProperty(User.class.getName() + ".SECURITY_243_FULL_DEFENSE", "true"));
private static final ThreadLocal<Boolean> resolving = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
@Override
public String resolveCanonicalId(String idOrFullName, Map<String, ?> context) {
User existing = getById(idOrFullName, false);
if (existing != null) {
return existing.getId();
}
if (SECURITY_243_FULL_DEFENSE) {
Jenkins j = Jenkins.getInstance();
if (j != null) {
if (!resolving.get()) {
resolving.set(true);
try {
return j.getSecurityRealm().loadUserByUsername(idOrFullName).getUsername();
} catch (UsernameNotFoundException x) {
LOGGER.log(Level.FINE, "not sure whether " + idOrFullName + " is a valid username or not", x);
} catch (DataAccessException x) {
LOGGER.log(Level.FINE, "could not look up " + idOrFullName, x);
} finally {
resolving.set(false);
}
}
}
}
return null;
}
@Override
public int getPriority() {
// should always come first so that ID that are ids get mapped correctly
return Integer.MAX_VALUE;
}
}
/**
* Jenkins now refuses to let the user login if he/she doesn't exist in {@link SecurityRealm},
* which was necessary to make sure users removed from the backend will get removed from the frontend.
* <p>
* Unfortunately this infringed some legitimate use cases of creating Jenkins-local users for
* automation purposes. This escape hatch switch can be enabled to resurrect that behaviour.
*
* JENKINS-22346.
*/
public static boolean ALLOW_NON_EXISTENT_USER_TO_LOGIN = Boolean.getBoolean(User.class.getName()+".allowNonExistentUserToLogin");
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_3058_0 |
crossvul-java_data_bad_2031_1 | package org.jolokia.http;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.management.RuntimeMBeanException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jolokia.backend.BackendManager;
import org.jolokia.config.*;
import org.jolokia.discovery.DiscoveryMulticastResponder;
import org.jolokia.restrictor.*;
import org.jolokia.util.*;
import org.json.simple.JSONAware;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Agent servlet which connects to a local JMX MBeanServer for
* JMX operations.
*
* <p>
* It uses a REST based approach which translates a GET Url into a
* request. See the <a href="http://www.jolokia.org/reference/index.html">reference documentation</a>
* for a detailed description of this servlet's features.
* </p>
*
* @author roland@jolokia.org
* @since Apr 18, 2009
*/
public class AgentServlet extends HttpServlet {
private static final long serialVersionUID = 42L;
// POST- and GET- HttpRequestHandler
private ServletRequestHandler httpGetHandler, httpPostHandler;
// Backend dispatcher
private BackendManager backendManager;
// Used for logging
private LogHandler logHandler;
// Request handler for parsing request parameters and building up a response
private HttpRequestHandler requestHandler;
// Restrictor to use as given in the constructor
private Restrictor restrictor;
// Mime type used for returning the answer
private String configMimeType;
// Listen for discovery request (if switched on)
private DiscoveryMulticastResponder discoveryMulticastResponder;
// If discovery multicast is enabled and URL should be initialized by request
private boolean initAgentUrlFromRequest = false;
/**
* No argument constructor, used e.g. by an servlet
* descriptor when creating the servlet out of web.xml
*/
public AgentServlet() {
this(null);
}
/**
* Constructor taking a restrictor to use
*
* @param pRestrictor restrictor to use or <code>null</code> if the restrictor
* should be created in the default way ({@link #createRestrictor(String)})
*/
public AgentServlet(Restrictor pRestrictor) {
restrictor = pRestrictor;
}
/**
* Get the installed log handler
*
* @return loghandler used for logging.
*/
protected LogHandler getLogHandler() {
return logHandler;
}
/**
* Create a restrictor restrictor to use. By default, a policy file
* is looked up (with the URL given by the init parameter {@link ConfigKey#POLICY_LOCATION}
* or "/jolokia-access.xml" by default) and if not found an {@link AllowAllRestrictor} is
* used by default. This method is called during the {@link #init(ServletConfig)} when initializing
* the subsystems and can be overridden for custom restrictor creation.
*
* @param pLocation location to lookup the restrictor
* @return the restrictor to use.
*/
protected Restrictor createRestrictor(String pLocation) {
LogHandler log = getLogHandler();
try {
Restrictor newRestrictor = RestrictorFactory.lookupPolicyRestrictor(pLocation);
if (newRestrictor != null) {
log.info("Using access restrictor " + pLocation);
return newRestrictor;
} else {
log.info("No access restrictor found at " + pLocation + ", access to all MBeans is allowed");
return new AllowAllRestrictor();
}
} catch (IOException e) {
log.error("Error while accessing access restrictor at " + pLocation +
". Denying all access to MBeans for security reasons. Exception: " + e, e);
return new DenyAllRestrictor();
}
}
/**
* Initialize the backend systems, the log handler and the restrictor. A subclass can tune
* this step by overriding {@link #createRestrictor(String)} and {@link #createLogHandler(ServletConfig, boolean)}
*
* @param pServletConfig servlet configuration
*/
@Override
public void init(ServletConfig pServletConfig) throws ServletException {
super.init(pServletConfig);
Configuration config = initConfig(pServletConfig);
// Create a log handler early in the lifecycle, but not too early
String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS);
logHandler = logHandlerClass != null ?
(LogHandler) ClassUtil.newInstance(logHandlerClass) :
createLogHandler(pServletConfig,Boolean.valueOf(config.get(ConfigKey.DEBUG)));
// Different HTTP request handlers
httpGetHandler = newGetHttpRequestHandler();
httpPostHandler = newPostHttpRequestHandler();
if (restrictor == null) {
restrictor = createRestrictor(config.get(ConfigKey.POLICY_LOCATION));
} else {
logHandler.info("Using custom access restriction provided by " + restrictor);
}
configMimeType = config.get(ConfigKey.MIME_TYPE);
backendManager = new BackendManager(config,logHandler, restrictor);
requestHandler = new HttpRequestHandler(config,backendManager,logHandler);
initDiscoveryMulticast(config);
}
private void initDiscoveryMulticast(Configuration pConfig) {
String url = findAgentUrl(pConfig);
if (url != null || listenForDiscoveryMcRequests(pConfig)) {
if (url == null) {
initAgentUrlFromRequest = true;
} else {
initAgentUrlFromRequest = false;
backendManager.getAgentDetails().updateAgentParameters(url, null);
}
try {
discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager,restrictor,logHandler);
discoveryMulticastResponder.start();
} catch (IOException e) {
logHandler.error("Cannot start discovery multicast handler: " + e,e);
}
}
}
// Try to find an URL for system props or config
private String findAgentUrl(Configuration pConfig) {
// System property has precedence
String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
if (url == null) {
url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
if (url == null) {
url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
}
}
return NetworkUtil.replaceExpression(url);
}
// For war agent needs to be switched on
private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
// Check for system props, system env and agent config
boolean sysProp = System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
return sysProp || env || config;
}
/**
* Create a log handler using this servlet's logging facility for logging. This method can be overridden
* to provide a custom log handler. This method is called before {@link #createRestrictor(String)} so the log handler
* can already be used when building up the restrictor.
*
* @return a default log handler
* @param pServletConfig servlet config from where to get information to build up the log handler
* @param pDebug whether to print out debug information.
*/
protected LogHandler createLogHandler(ServletConfig pServletConfig, final boolean pDebug) {
return new LogHandler() {
/** {@inheritDoc} */
public void debug(String message) {
if (pDebug) {
log(message);
}
}
/** {@inheritDoc} */
public void info(String message) {
log(message);
}
/** {@inheritDoc} */
public void error(String message, Throwable t) {
log(message,t);
}
};
}
/** {@inheritDoc} */
@Override
public void destroy() {
backendManager.destroy();
if (discoveryMulticastResponder != null) {
discoveryMulticastResponder.stop();
discoveryMulticastResponder = null;
}
super.destroy();
}
/** {@inheritDoc} */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handle(httpGetHandler,req, resp);
}
/** {@inheritDoc} */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handle(httpPostHandler,req,resp);
}
/**
* OPTION requests are treated as CORS preflight requests
*
* @param req the original request
* @param resp the response the answer are written to
* */
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String,String> responseHeaders =
requestHandler.handleCorsPreflightRequest(
req.getHeader("Origin"),
req.getHeader("Access-Control-Request-Headers"));
for (Map.Entry<String,String> entry : responseHeaders.entrySet()) {
resp.setHeader(entry.getKey(),entry.getValue());
}
}
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" })
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
JSONAware json = null;
try {
// Check access policy
requestHandler.checkClientIPAccess(pReq.getRemoteHost(),pReq.getRemoteAddr());
// Remember the agent URL upon the first request. Needed for discovery
updateAgentUrlIfNeeded(pReq);
// Dispatch for the proper HTTP request method
json = pReqHandler.handleRequest(pReq,pResp);
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
setCorsHeader(pReq, pResp);
String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
String answer = json != null ?
json.toJSONString() :
requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
if (callback != null) {
// Send a JSONP response
sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
} else {
sendResponse(pResp, getMimeType(pReq),answer);
}
}
}
// Update the agent URL in the agent details if not already done
private void updateAgentUrlIfNeeded(HttpServletRequest pReq) {
// Lookup the Agent URL if needed
if (initAgentUrlFromRequest) {
updateAgentUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()), extractServletPath(pReq),pReq.getAuthType() != null);
initAgentUrlFromRequest = false;
}
}
private String extractServletPath(HttpServletRequest pReq) {
return pReq.getRequestURI().substring(0,pReq.getContextPath().length());
}
// Update the URL in the AgentDetails
private void updateAgentUrl(String pRequestUrl, String pServletPath, boolean pIsAuthenticated) {
String url = getBaseUrl(pRequestUrl, pServletPath);
backendManager.getAgentDetails().updateAgentParameters(url,pIsAuthenticated);
}
// Strip off everything unneeded
private String getBaseUrl(String pUrl, String pServletPath) {
String sUrl;
try {
URL url = new URL(pUrl);
String host = getIpIfPossible(url.getHost());
sUrl = new URL(url.getProtocol(),host,url.getPort(),pServletPath).toExternalForm();
} catch (MalformedURLException exp) {
sUrl = plainReplacement(pUrl, pServletPath);
}
return sUrl;
}
// Check for an IP, since this seems to be safer to return then a plain name
private String getIpIfPossible(String pHost) {
try {
InetAddress address = InetAddress.getByName(pHost);
return address.getHostAddress();
} catch (UnknownHostException e) {
return pHost;
}
}
// Fallback used if URL creation didnt work
private String plainReplacement(String pUrl, String pServletPath) {
int idx = pUrl.lastIndexOf(pServletPath);
String url;
if (idx != -1) {
url = pUrl.substring(0,idx) + pServletPath;
} else {
url = pUrl;
}
return url;
}
// Set an appropriate CORS header if requested and if allowed
private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
if (origin != null) {
pResp.setHeader("Access-Control-Allow-Origin", origin);
pResp.setHeader("Access-Control-Allow-Credentials","true");
}
}
// Extract mime type for response (if not JSONP)
private String getMimeType(HttpServletRequest pReq) {
String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
if (requestMimeType != null) {
return requestMimeType;
}
return configMimeType;
}
private interface ServletRequestHandler {
/**
* Handle a request and return the answer as a JSON structure
* @param pReq request arrived
* @param pResp response to return
* @return the JSON representation for the answer
* @throws IOException if handling of an input or output stream failed
*/
JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
throws IOException;
}
// factory method for POST request handler
private ServletRequestHandler newPostHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
throws IOException {
String encoding = pReq.getCharacterEncoding();
InputStream is = pReq.getInputStream();
return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq));
}
};
}
// factory method for GET request handler
private ServletRequestHandler newGetHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) {
return requestHandler.handleGetRequest(pReq.getRequestURI(),pReq.getPathInfo(), getParameterMap(pReq));
}
};
}
// =======================================================================
// Get parameter map either directly from an Servlet 2.4 compliant implementation
// or by looking it up explictely (thanks to codewax for the patch)
private Map<String, String[]> getParameterMap(HttpServletRequest pReq){
try {
// Servlet 2.4 API
return pReq.getParameterMap();
} catch (UnsupportedOperationException exp) {
// Thrown by 'pseudo' 2.4 Servlet API implementations which fake a 2.4 API
// As a service for the parameter map is build up explicitely
Map<String, String[]> ret = new HashMap<String, String[]>();
Enumeration params = pReq.getParameterNames();
while (params.hasMoreElements()) {
String param = (String) params.nextElement();
ret.put(param, pReq.getParameterValues(param));
}
return ret;
}
}
// Examines servlet config and servlet context for configuration parameters.
// Configuration from the servlet context overrides servlet parameters defined in web.xml
Configuration initConfig(ServletConfig pConfig) {
Configuration config = new Configuration(
ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(),"servlet"));
// From ServletContext ....
config.updateGlobalConfiguration(new ServletConfigFacade(pConfig));
// ... and ServletConfig
config.updateGlobalConfiguration(new ServletContextFacade(getServletContext()));
// Set type last and overwrite anything written
config.updateGlobalConfiguration(Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(),"servlet"));
return config;
}
private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt) throws IOException {
setContentType(pResp, pContentType);
pResp.setStatus(200);
setNoCacheHeaders(pResp);
PrintWriter writer = pResp.getWriter();
writer.write(pJsonTxt);
}
private void setNoCacheHeaders(HttpServletResponse pResp) {
pResp.setHeader("Cache-Control", "no-cache");
pResp.setHeader("Pragma","no-cache");
// Check for a date header and set it accordingly to the recommendations of
// RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21)
//
// "To mark a response as "already expired," an origin server sends an
// Expires date that is equal to the Date header value. (See the rules
// for expiration calculations in section 13.2.4.)"
//
// See also #71
long now = System.currentTimeMillis();
pResp.setDateHeader("Date",now);
// 1h in the past since it seems, that some servlet set the date header on their
// own so that it cannot be guaranteed that these headers are really equals.
// It happened on Tomcat that Date: was finally set *before* Expires: in the final
// answers some times which seems to be an implementation peculiarity from Tomcat
pResp.setDateHeader("Expires",now - 3600000);
}
private void setContentType(HttpServletResponse pResp, String pContentType) {
boolean encodingDone = false;
try {
pResp.setCharacterEncoding("utf-8");
pResp.setContentType(pContentType);
encodingDone = true;
}
catch (NoSuchMethodError error) { /* Servlet 2.3 */ }
catch (UnsupportedOperationException error) { /* Equinox HTTP Service */ }
if (!encodingDone) {
// For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand
pResp.setContentType(pContentType + "; charset=utf-8");
}
}
// =======================================================================================
// Helper classes for extracting configuration from servlet classes
// Implementation for the ServletConfig
private static final class ServletConfigFacade implements ConfigExtractor {
private final ServletConfig config;
private ServletConfigFacade(ServletConfig pConfig) {
config = pConfig;
}
/** {@inheritDoc} */
public Enumeration getNames() {
return config.getInitParameterNames();
}
/** {@inheritDoc} */
public String getParameter(String pName) {
return config.getInitParameter(pName);
}
}
// Implementation for ServletContextFacade
private static final class ServletContextFacade implements ConfigExtractor {
private final ServletContext servletContext;
private ServletContextFacade(ServletContext pServletContext) {
servletContext = pServletContext;
}
/** {@inheritDoc} */
public Enumeration getNames() {
return servletContext.getInitParameterNames();
}
/** {@inheritDoc} */
public String getParameter(String pName) {
return servletContext.getInitParameter(pName);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_1 |
crossvul-java_data_bad_5842_10 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.fibu;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.convert.IConverter;
import org.projectforge.common.NumberHelper;
import org.projectforge.core.Constants;
import org.projectforge.core.CurrencyFormatter;
import org.projectforge.core.NumberFormatter;
import org.projectforge.fibu.AbstractRechnungsPositionDO;
import org.projectforge.fibu.EingangsrechnungsPositionDO;
import org.projectforge.fibu.ProjektDO;
import org.projectforge.fibu.RechnungDO;
import org.projectforge.fibu.RechnungsPositionDO;
import org.projectforge.fibu.kost.Kost1DO;
import org.projectforge.fibu.kost.Kost2DO;
import org.projectforge.fibu.kost.Kost2Dao;
import org.projectforge.fibu.kost.KostZuweisungDO;
import org.projectforge.fibu.kost.KostZuweisungenCopyHelper;
import org.projectforge.web.wicket.WicketAjaxUtils;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.components.MinMaxNumberField;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.converter.CurrencyConverter;
import org.projectforge.web.wicket.flowlayout.ButtonPanel;
import org.projectforge.web.wicket.flowlayout.IconButtonPanel;
import org.projectforge.web.wicket.flowlayout.IconType;
import org.projectforge.web.wicket.flowlayout.MyAjaxComponentHolder;
/**
* @author Kai Reinhard (k.reinhard@micromata.de)
*
*/
public class RechnungCostEditTablePanel extends Panel
{
private static final long serialVersionUID = -5732520730823126042L;
private final RepeatingView rows;
private final Form<AbstractRechnungsPositionDO> form;
private final FeedbackPanel feedbackPanel;
@SpringBean(name = "kost2Dao")
private Kost2Dao kost2Dao;
private AbstractRechnungsPositionDO position;
MyAjaxComponentHolder ajaxComponents = new MyAjaxComponentHolder();
/**
* @param id
*/
public RechnungCostEditTablePanel(final String id)
{
super(id);
feedbackPanel = new FeedbackPanel("feedback");
ajaxComponents.register(feedbackPanel);
add(feedbackPanel);
this.form = new Form<AbstractRechnungsPositionDO>("form");
add(form);
rows = new RepeatingView("rows");
form.add(rows);
}
/**
* @return the position
*/
public AbstractRechnungsPositionDO getPosition()
{
return position;
}
@SuppressWarnings("serial")
public RechnungCostEditTablePanel add(final AbstractRechnungsPositionDO origPosition)
{
if (origPosition instanceof RechnungsPositionDO) {
position = new RechnungsPositionDO();
} else {
position = new EingangsrechnungsPositionDO();
}
position.copyValuesFrom(origPosition, "kostZuweisungen");
new KostZuweisungenCopyHelper().mycopy(origPosition.getKostZuweisungen(), null, position);
List<KostZuweisungDO> kostzuweisungen = position.getKostZuweisungen();
if (CollectionUtils.isEmpty(kostzuweisungen) == true) {
addZuweisung(position);
kostzuweisungen = position.getKostZuweisungen();
}
for (final KostZuweisungDO zuweisung : kostzuweisungen) {
final WebMarkupContainer row = createRow(rows.newChildId(), position, zuweisung);
rows.add(row);
}
final Label restLabel = new Label("restValue", new Model<String>() {
/**
* @see org.apache.wicket.model.Model#getObject()
*/
@Override
public String getObject()
{
return CurrencyFormatter.format(position.getKostZuweisungNetFehlbetrag());
}
});
form.add(restLabel);
ajaxComponents.register(restLabel);
final AjaxButton addRowButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
final KostZuweisungDO zuweisung = addZuweisung(position);
final WebMarkupContainer newRow = createRow(rows.newChildId(), position, zuweisung);
newRow.setOutputMarkupId(true);
final StringBuffer prependJavascriptBuf = new StringBuffer();
prependJavascriptBuf.append(WicketAjaxUtils.appendChild("costAssignmentBody", "tr", newRow.getMarkupId()));
rows.add(newRow);
target.add(newRow);
ajaxComponents.addTargetComponents(target);
target.prependJavaScript(prependJavascriptBuf.toString());
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel);
}
};
// addRowButton.setDefaultFormProcessing(false);
final SingleButtonPanel addPositionButtonPanel = new SingleButtonPanel("addRowButton", addRowButton, getString("add"));
form.add(addPositionButtonPanel);
final AjaxButton recalculateButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
ajaxComponents.addTargetComponents(target);
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel);
}
};
// recalculateButton.setDefaultFormProcessing(false);
final SingleButtonPanel recalculateButtonPanel = new SingleButtonPanel("recalculateButton", recalculateButton, getString("recalculate"));
form.add(recalculateButtonPanel);
return this;
}
@SuppressWarnings("serial")
private WebMarkupContainer createRow(final String id, final AbstractRechnungsPositionDO position, final KostZuweisungDO zuweisung)
{
final WebMarkupContainer row = new WebMarkupContainer(id);
row.setOutputMarkupId(true);
final Kost1FormComponent kost1 = new Kost1FormComponent("kost1", new PropertyModel<Kost1DO>(zuweisung, "kost1"), true);
kost1.setLabel(new Model<String>(getString("fibu.kost1")));
row.add(kost1);
ajaxComponents.register(kost1);
final Kost2FormComponent kost2 = new Kost2FormComponent("kost2", new PropertyModel<Kost2DO>(zuweisung, "kost2"), true);
kost2.setLabel(new Model<String>(getString("fibu.kost2")));
row.add(kost2);
ajaxComponents.register(kost2);
final MinMaxNumberField<BigDecimal> netto = new MinMaxNumberField<BigDecimal>("netto",
new PropertyModel<BigDecimal>(zuweisung, "netto"), Constants.TEN_BILLION_NEGATIVE, Constants.TEN_BILLION) {
@SuppressWarnings({ "rawtypes", "unchecked"})
@Override
public IConverter getConverter(final Class type)
{
return new CurrencyConverter(position.getNetSum());
}
};
netto.setLabel(new Model<String>(getString("fibu.common.netto")));
WicketUtils.addTooltip(netto, getString("currencyConverter.percentage.help"));
row.add(netto);
ajaxComponents.register(netto); // Should be updated if e. g. percentage value is given.
final Label pLabel = new Label("percentage", new Model<String>() {
/**
* @see org.apache.wicket.model.Model#getObject()
*/
@Override
public String getObject()
{
final BigDecimal percentage;
if (NumberHelper.isZeroOrNull(position.getNetSum()) == true || NumberHelper.isZeroOrNull(zuweisung.getNetto()) == true) {
percentage = BigDecimal.ZERO;
} else {
percentage = zuweisung.getNetto().divide(position.getNetSum(), RoundingMode.HALF_UP);
}
final boolean percentageVisible = NumberHelper.isNotZero(percentage);
if (percentageVisible == true) {
return NumberFormatter.formatPercent(percentage);
} else {
return " ";
}
}
});
ajaxComponents.register(pLabel);
row.add(pLabel);
if (position.isKostZuweisungDeletable(zuweisung) == true) {
final AjaxButton deleteRowButton = new AjaxButton(ButtonPanel.BUTTON_ID, form) {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
position.deleteKostZuweisung(zuweisung.getIndex());
final StringBuffer prependJavascriptBuf = new StringBuffer();
prependJavascriptBuf.append(WicketAjaxUtils.removeChild("costAssignmentBody", row.getMarkupId()));
ajaxComponents.remove(row);
rows.remove(row);
target.prependJavaScript(prependJavascriptBuf.toString());
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
target.add(feedbackPanel.setVisible(true));
}
};
deleteRowButton.setDefaultFormProcessing(false);
row.add(new IconButtonPanel("deleteEntry", deleteRowButton, IconType.TRASH, null).setLight());
} else {
// Don't show a delete button.
row.add(new Label("deleteEntry", " ").setEscapeModelStrings(false).setRenderBodyOnly(true));
}
return row;
}
private KostZuweisungDO addZuweisung(final AbstractRechnungsPositionDO position)
{
final KostZuweisungDO kostZuweisung = new KostZuweisungDO();
position.addKostZuweisung(kostZuweisung);
if (kostZuweisung.getIndex() > 0) {
final KostZuweisungDO predecessor = position.getKostZuweisung(kostZuweisung.getIndex() - 1);
if (predecessor != null) {
kostZuweisung.setKost1(predecessor.getKost1()); // Preset kost1 from the predecessor position.
kostZuweisung.setKost2(predecessor.getKost2()); // Preset kost2 from the predecessor position.
}
}
if (RechnungsPositionDO.class.isAssignableFrom(position.getClass()) == true && kostZuweisung.getKost2() == null) {
// Preset kost2 with first kost2 found for the projekt.
final RechnungsPositionDO rechnungsPosition = (RechnungsPositionDO) position;
if (rechnungsPosition != null) {
final RechnungDO rechnung = rechnungsPosition.getRechnung();
if (rechnung != null) {
final ProjektDO project = rechnung.getProjekt();
if (project != null) {
final List<Kost2DO> kost2List = kost2Dao.getActiveKost2(project);
if (CollectionUtils.isNotEmpty(kost2List) == true) {
kostZuweisung.setKost2(kost2List.get(0));
}
}
}
}
}
kostZuweisung.setNetto(position.getKostZuweisungNetFehlbetrag().negate());
return kostZuweisung;
}
/**
* @return the form
*/
public Form<AbstractRechnungsPositionDO> getForm()
{
return form;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_10 |
crossvul-java_data_good_2031_2 | package org.jolokia.http;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.management.*;
import org.jolokia.backend.BackendManager;
import org.jolokia.config.*;
import org.jolokia.request.JmxRequest;
import org.jolokia.request.JmxRequestFactory;
import org.jolokia.util.LogHandler;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Request handler with no dependency on the servlet API so that it can be used in
* several different environments (like for the Sun JDK 6 {@link com.sun.net.httpserver.HttpServer}.
*
* @author roland
* @since Mar 3, 2010
*/
public class HttpRequestHandler {
// handler for contacting the MBean server(s)
private BackendManager backendManager;
// Logging abstraction
private LogHandler logHandler;
// Global configuration
private Configuration config;
/**
* Request handler for parsing HTTP request and dispatching to the appropriate
* request handler (with help of the backend manager)
*
* @param pBackendManager backend manager to user
* @param pLogHandler log handler to where to put out logging
*/
public HttpRequestHandler(Configuration pConfig, BackendManager pBackendManager, LogHandler pLogHandler) {
backendManager = pBackendManager;
logHandler = pLogHandler;
config = pConfig;
}
/**
* Handle a GET request
*
* @param pUri URI leading to this request
* @param pPathInfo path of the request
* @param pParameterMap parameters of the GET request @return the response
*/
public JSONAware handleGetRequest(String pUri, String pPathInfo, Map<String, String[]> pParameterMap) {
String pathInfo = extractPathInfo(pUri, pPathInfo);
JmxRequest jmxReq =
JmxRequestFactory.createGetRequest(pathInfo,getProcessingParameter(pParameterMap));
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
logHandler.debug("Path-Info: " + pathInfo);
logHandler.debug("Request: " + jmxReq.toString());
}
return executeRequest(jmxReq);
}
private ProcessingParameters getProcessingParameter(Map<String, String[]> pParameterMap) {
Map<String,String> ret = new HashMap<String, String>();
if (pParameterMap != null) {
for (Map.Entry<String,String[]> entry : pParameterMap.entrySet()) {
String values[] = entry.getValue();
if (values != null && values.length > 0) {
ret.put(entry.getKey(), values[0]);
}
}
}
return config.getProcessingParameters(ret);
}
/**
* Handle the input stream as given by a POST request
*
*
* @param pUri URI leading to this request
* @param pInputStream input stream of the post request
* @param pEncoding optional encoding for the stream. If null, the default encoding is used
* @param pParameterMap additional processing parameters
* @return the JSON object containing the json results for one or more {@link JmxRequest} contained
* within the answer.
*
* @throws IOException if reading from the input stream fails
*/
public JSONAware handlePostRequest(String pUri, InputStream pInputStream, String pEncoding, Map<String, String[]> pParameterMap)
throws IOException {
if (backendManager.isDebug()) {
logHandler.debug("URI: " + pUri);
}
Object jsonRequest = extractJsonRequest(pInputStream,pEncoding);
if (jsonRequest instanceof JSONArray) {
List<JmxRequest> jmxRequests = JmxRequestFactory.createPostRequests((List) jsonRequest,getProcessingParameter(pParameterMap));
JSONArray responseList = new JSONArray();
for (JmxRequest jmxReq : jmxRequests) {
if (backendManager.isDebug()) {
logHandler.debug("Request: " + jmxReq.toString());
}
// Call handler and retrieve return value
JSONObject resp = executeRequest(jmxReq);
responseList.add(resp);
}
return responseList;
} else if (jsonRequest instanceof JSONObject) {
JmxRequest jmxReq = JmxRequestFactory.createPostRequest((Map<String, ?>) jsonRequest,getProcessingParameter(pParameterMap));
return executeRequest(jmxReq);
} else {
throw new IllegalArgumentException("Invalid JSON Request " + jsonRequest);
}
}
/**
* Handling an option request which is used for preflight checks before a CORS based browser request is
* sent (for certain circumstances).
*
* See the <a href="http://www.w3.org/TR/cors/">CORS specification</a>
* (section 'preflight checks') for more details.
*
* @param pOrigin the origin to check. If <code>null</code>, no headers are returned
* @param pRequestHeaders extra headers to check against
* @return headers to set
*/
public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
Map<String,String> ret = new HashMap<String, String>();
if (pOrigin != null && backendManager.isOriginAllowed(pOrigin,false)) {
// CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
if (pRequestHeaders != null) {
ret.put("Access-Control-Allow-Headers",pRequestHeaders);
}
// Fix for CORS with authentication (#104)
ret.put("Access-Control-Allow-Credentials","true");
// Allow for one year. Changes in access.xml are reflected directly in the cors request itself
ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
}
return ret;
}
private Object extractJsonRequest(InputStream pInputStream, String pEncoding) throws IOException {
InputStreamReader reader = null;
try {
reader =
pEncoding != null ?
new InputStreamReader(pInputStream, pEncoding) :
new InputStreamReader(pInputStream);
JSONParser parser = new JSONParser();
return parser.parse(reader);
} catch (ParseException exp) {
throw new IllegalArgumentException("Invalid JSON request " + reader,exp);
}
}
/**
* Execute a single {@link JmxRequest}. If a checked exception occurs,
* this gets translated into the appropriate JSON object which will get returned.
* Note, that these exceptions gets *not* translated into an HTTP error, since they are
* supposed <em>Jolokia</em> specific errors above the transport layer.
*
* @param pJmxReq the request to execute
* @return the JSON representation of the answer.
*/
private JSONObject executeRequest(JmxRequest pJmxReq) {
// Call handler and retrieve return value
try {
return backendManager.handleRequest(pJmxReq);
} catch (ReflectionException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (InstanceNotFoundException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (MBeanException e) {
return getErrorJSON(500,e.getTargetException(), pJmxReq);
} catch (AttributeNotFoundException e) {
return getErrorJSON(404,e, pJmxReq);
} catch (UnsupportedOperationException e) {
return getErrorJSON(500,e, pJmxReq);
} catch (IOException e) {
return getErrorJSON(500,e, pJmxReq);
} catch (IllegalArgumentException e) {
return getErrorJSON(400,e, pJmxReq);
} catch (SecurityException e) {
// Wipe out stacktrace
return getErrorJSON(403,new Exception(e.getMessage()), pJmxReq);
} catch (RuntimeMBeanException e) {
// Use wrapped exception
return errorForUnwrappedException(e,pJmxReq);
}
}
/**
* Utility method for handling single runtime exceptions and errors. This method is called
* in addition to and after {@link #executeRequest(JmxRequest)} to catch additional errors.
* They are two different methods because of bulk requests, where each individual request can
* lead to an error. So, each individual request is wrapped with the error handling of
* {@link #executeRequest(JmxRequest)}
* whereas the overall handling is wrapped with this method. It is hence more coarse grained,
* leading typically to an status code of 500.
*
* Summary: This method should be used as last security belt is some exception should escape
* from a single request processing in {@link #executeRequest(JmxRequest)}.
*
* @param pThrowable exception to handle
* @return its JSON representation
*/
public JSONObject handleThrowable(Throwable pThrowable) {
if (pThrowable instanceof IllegalArgumentException) {
return getErrorJSON(400,pThrowable, null);
} else if (pThrowable instanceof SecurityException) {
// Wipe out stacktrace
return getErrorJSON(403,new Exception(pThrowable.getMessage()), null);
} else {
return getErrorJSON(500,pThrowable, null);
}
}
/**
* Get the JSON representation for a an exception
*
*
* @param pErrorCode the HTTP error code to return
* @param pExp the exception or error occured
* @param pJmxReq request from where to get processing options
* @return the json representation
*/
public JSONObject getErrorJSON(int pErrorCode, Throwable pExp, JmxRequest pJmxReq) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status",pErrorCode);
jsonObject.put("error",getExceptionMessage(pExp));
jsonObject.put("error_type", pExp.getClass().getName());
addErrorInfo(jsonObject, pExp, pJmxReq);
if (backendManager.isDebug()) {
backendManager.error("Error " + pErrorCode,pExp);
}
if (pJmxReq != null) {
jsonObject.put("request",pJmxReq.toJSON());
}
return jsonObject;
}
/**
* Check whether the given host and/or address is allowed to access this agent.
*
* @param pHost host to check
* @param pAddress address to check
* @param pOrigin (optional) origin header to check also.
*/
public void checkAccess(String pHost, String pAddress, String pOrigin) {
if (!backendManager.isRemoteAccessAllowed(pHost,pAddress)) {
throw new SecurityException("No access from client " + pAddress + " allowed");
}
if (pOrigin != null && !backendManager.isOriginAllowed(pOrigin,true)) {
throw new SecurityException("Origin " + pOrigin + " is not allowed to call this agent");
}
}
/**
* Check whether for the given host is a cross-browser request allowed. This check is delegated to the
* backendmanager which is responsible for the security configuration.
* Also, some sanity checks are applied.
*
* @param pOrigin the origin URL to check against
* @return the origin to put in the response header or null if none is to be set
*/
public String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isOriginAllowed(origin,false)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
}
private void addErrorInfo(JSONObject pErrorResp, Throwable pExp, JmxRequest pJmxReq) {
String includeStackTrace = pJmxReq != null ?
pJmxReq.getParameter(ConfigKey.INCLUDE_STACKTRACE) : "true";
if (includeStackTrace.equalsIgnoreCase("true") ||
(includeStackTrace.equalsIgnoreCase("runtime") && pExp instanceof RuntimeException)) {
StringWriter writer = new StringWriter();
pExp.printStackTrace(new PrintWriter(writer));
pErrorResp.put("stacktrace",writer.toString());
}
if (pJmxReq != null && pJmxReq.getParameterAsBool(ConfigKey.SERIALIZE_EXCEPTION)) {
pErrorResp.put("error_value",backendManager.convertExceptionToJson(pExp,pJmxReq));
}
}
// Extract class and exception message for an error message
private String getExceptionMessage(Throwable pException) {
String message = pException.getLocalizedMessage();
return pException.getClass().getName() + (message != null ? " : " + message : "");
}
// Unwrap an exception to get to the 'real' exception
// and extract the error code accordingly
private JSONObject errorForUnwrappedException(Exception e, JmxRequest pJmxReq) {
Throwable cause = e.getCause();
int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500;
return getErrorJSON(code,cause, pJmxReq);
}
// Path info might need some special handling in case when the URL
// contains two following slashes. These slashes get collapsed
// when calling getPathInfo() but are still present in the URI.
// This situation can happen, when slashes are escaped and the last char
// of an path part is such an escaped slash
// (e.g. "read/domain:type=name!//attribute")
// In this case, we extract the path info on our own
private static final Pattern PATH_PREFIX_PATTERN = Pattern.compile("^/?[^/]+/");
private String extractPathInfo(String pUri, String pPathInfo) {
if (pUri.contains("!//")) {
// Special treatment for trailing slashes in paths
Matcher matcher = PATH_PREFIX_PATTERN.matcher(pPathInfo);
if (matcher.find()) {
String prefix = matcher.group();
String pathInfoEncoded = pUri.replaceFirst("^.*?" + prefix, prefix);
try {
return URLDecoder.decode(pathInfoEncoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Should not happen at all ... so we silently fall through
}
}
}
return pPathInfo;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_2 |
crossvul-java_data_good_5842_6 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.core;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.projectforge.access.AccessChecker;
import org.projectforge.user.PFUserContext;
import org.projectforge.user.UserRights;
import org.projectforge.user.UserXmlPreferencesCache;
import org.projectforge.web.FavoritesMenu;
import org.projectforge.web.LayoutSettingsPage;
import org.projectforge.web.LoginPage;
import org.projectforge.web.MenuEntry;
import org.projectforge.web.core.menuconfig.MenuConfig;
import org.projectforge.web.dialog.ModalDialog;
import org.projectforge.web.doc.DocumentationPage;
import org.projectforge.web.mobile.MenuMobilePage;
import org.projectforge.web.user.ChangePasswordPage;
import org.projectforge.web.user.MyAccountEditPage;
import org.projectforge.web.wicket.AbstractSecuredPage;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.FeedbackPage;
import org.projectforge.web.wicket.MySession;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
/**
* Displays the favorite menu.
* @author Kai Reinhard (k.reinhard@micromata.de)
*/
public class NavTopPanel extends NavAbstractPanel
{
private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(NavTopPanel.class);
private static final long serialVersionUID = -7858806882044188339L;
private FavoritesMenu favoritesMenu;
private final AccessChecker accessChecker;
private final UserXmlPreferencesCache userXmlPreferencesCache;
private BookmarkDialog bookmarkDialog;
/**
* Cross site request forgery token.
*/
private CsrfTokenHandler csrfTokenHandler;
public NavTopPanel(final String id, final UserXmlPreferencesCache userXmlPreferencesCache, final AccessChecker accessChecker)
{
super(id);
this.userXmlPreferencesCache = userXmlPreferencesCache;
this.accessChecker = accessChecker;
}
public void init(final AbstractSecuredPage page)
{
getMenu();
this.favoritesMenu = FavoritesMenu.get();
final WebMarkupContainer goMobile = new WebMarkupContainer("goMobile");
add(goMobile);
if (page.getMySession().isMobileUserAgent() == true) {
goMobile.add(new BookmarkablePageLink<Void>("link", MenuMobilePage.class));
} else {
goMobile.setVisible(false);
}
final BookmarkablePageLink<Void> layoutSettingsMenuLink = new BookmarkablePageLink<Void>("layoutSettingsMenuLink",
LayoutSettingsPage.class);
if (UserRights.getAccessChecker().isRestrictedUser() == true) {
// Not visibible for restricted users:
layoutSettingsMenuLink.setVisible(false);
}
add(new MenuConfig("menuconfig", getMenu(), favoritesMenu));
@SuppressWarnings("serial")
final Form<String> searchForm = new Form<String>("searchForm") {
private String searchString;
/**
* @see org.apache.wicket.markup.html.form.Form#onSubmit()
*/
@Override
protected void onSubmit()
{
csrfTokenHandler.onSubmit();
if (StringUtils.isNotBlank(searchString) == true) {
final SearchPage searchPage = new SearchPage(new PageParameters(), searchString);
setResponsePage(searchPage);
}
super.onSubmit();
}
};
csrfTokenHandler = new CsrfTokenHandler(searchForm);
add(searchForm);
final TextField<String> searchField = new TextField<String>("searchField", new PropertyModel<String>(searchForm, "searchString"));
WicketUtils.setPlaceHolderAttribute(searchField, getString("search.search"));
searchForm.add(searchField);
add(layoutSettingsMenuLink);
add(new BookmarkablePageLink<Void>("feedbackLink", FeedbackPage.class));
{
@SuppressWarnings("serial")
final AjaxLink<Void> showBookmarkLink = new AjaxLink<Void>("showBookmarkLink") {
/**
* @see org.apache.wicket.ajax.markup.html.AjaxLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
*/
@Override
public void onClick(final AjaxRequestTarget target)
{
bookmarkDialog.open(target);
// Redraw the content:
bookmarkDialog.redraw().addContent(target);
}
};
add(showBookmarkLink);
addBookmarkDialog();
}
{
add(new Label("user", PFUserContext.getUser().getFullname()));
if (accessChecker.isRestrictedUser() == true) {
// Show ChangePaswordPage as my account for restricted users.
final BookmarkablePageLink<Void> changePasswordLink = new BookmarkablePageLink<Void>("myAccountLink", ChangePasswordPage.class);
add(changePasswordLink);
} else {
final BookmarkablePageLink<Void> myAccountLink = new BookmarkablePageLink<Void>("myAccountLink", MyAccountEditPage.class);
add(myAccountLink);
}
final BookmarkablePageLink<Void> documentationLink = new BookmarkablePageLink<Void>("documentationLink", DocumentationPage.class);
add(documentationLink);
@SuppressWarnings("serial")
final Link<String> logoutLink = new Link<String>("logoutLink") {
@Override
public void onClick()
{
LoginPage.logout((MySession) getSession(), (WebRequest) getRequest(), (WebResponse) getResponse(), userXmlPreferencesCache);
setResponsePage(LoginPage.class);
};
};
add(logoutLink);
}
addCompleteMenu();
addFavoriteMenu();
}
@SuppressWarnings("serial")
private void addCompleteMenu()
{
final Label totalMenuSuffixLabel = new MenuSuffixLabel("totalMenuCounter", new Model<Integer>() {
@Override
public Integer getObject()
{
int counter = 0;
if (menu.getMenuEntries() == null) {
return counter;
}
for (final MenuEntry menuEntry : menu.getMenuEntries()) {
final IModel<Integer> newCounterModel = menuEntry.getNewCounterModel();
if (newCounterModel != null && newCounterModel.getObject() != null) {
counter += newCounterModel.getObject();
}
}
return counter;
};
});
add(totalMenuSuffixLabel);
final RepeatingView completeMenuCategoryRepeater = new RepeatingView("completeMenuCategoryRepeater");
add(completeMenuCategoryRepeater);
if (menu.getMenuEntries() != null) {
for (final MenuEntry menuEntry : menu.getMenuEntries()) {
if (menuEntry.getSubMenuEntries() == null) {
continue;
}
// Now we add a new menu area (title with sub menus):
final WebMarkupContainer categoryContainer = new WebMarkupContainer(completeMenuCategoryRepeater.newChildId());
completeMenuCategoryRepeater.add(categoryContainer);
categoryContainer.add(new Label("menuCategoryLabel", getString(menuEntry.getI18nKey())));
final Label areaSuffixLabel = getSuffixLabel(menuEntry);
categoryContainer.add(areaSuffixLabel);
// final WebMarkupContainer subMenuContainer = new WebMarkupContainer("subMenu");
// categoryContainer.add(subMenuContainer);
if (menuEntry.hasSubMenuEntries() == false) {
// subMenuContainer.setVisible(false);
continue;
}
final RepeatingView completeSubMenuRepeater = new RepeatingView("completeSubMenuRepeater");
categoryContainer.add(completeSubMenuRepeater);
for (final MenuEntry subMenuEntry : menuEntry.getSubMenuEntries()) {
if (subMenuEntry.getSubMenuEntries() != null) {
log.error("Oups: sub sub menus not supported: " + menuEntry.getId() + " has child menus which are ignored.");
}
// Now we add the next menu entry to the area:
final WebMarkupContainer subMenuItem = new WebMarkupContainer(completeSubMenuRepeater.newChildId());
completeSubMenuRepeater.add(subMenuItem);
final AbstractLink link = getMenuEntryLink(subMenuEntry, true);
if (link != null) {
subMenuItem.add(link);
} else {
subMenuItem.setVisible(false);
}
}
}
}
}
private void addFavoriteMenu()
{
// Favorite menu:
final RepeatingView menuRepeater = new RepeatingView("menuRepeater");
add(menuRepeater);
final Collection<MenuEntry> menuEntries = favoritesMenu.getMenuEntries();
if (menuEntries != null) {
for (final MenuEntry menuEntry : menuEntries) {
// Now we add a new menu area (title with sub menus):
final WebMarkupContainer menuItem = new WebMarkupContainer(menuRepeater.newChildId());
menuRepeater.add(menuItem);
final AbstractLink link = getMenuEntryLink(menuEntry, true);
if (link == null) {
menuItem.setVisible(false);
continue;
}
menuItem.add(link);
final WebMarkupContainer subMenuContainer = new WebMarkupContainer("subMenu");
menuItem.add(subMenuContainer);
final WebMarkupContainer caret = new WebMarkupContainer("caret");
link.add(caret);
if (menuEntry.hasSubMenuEntries() == false) {
subMenuContainer.setVisible(false);
caret.setVisible(false);
continue;
}
menuItem.add(AttributeModifier.append("class", "dropdown"));
link.add(AttributeModifier.append("class", "dropdown-toggle"));
link.add(AttributeModifier.append("data-toggle", "dropdown"));
final RepeatingView subMenuRepeater = new RepeatingView("subMenuRepeater");
subMenuContainer.add(subMenuRepeater);
for (final MenuEntry subMenuEntry : menuEntry.getSubMenuEntries()) {
// Now we add the next menu entry to the area:
if (subMenuEntry.hasSubMenuEntries() == false) {
final WebMarkupContainer subMenuItem = new WebMarkupContainer(subMenuRepeater.newChildId());
subMenuRepeater.add(subMenuItem);
// Subsubmenu entries aren't yet supported, show only the sub entries without children, otherwise only the children are
// displayed.
final AbstractLink subLink = getMenuEntryLink(subMenuEntry, true);
if (subLink == null) {
subMenuItem.setVisible(false);
continue;
}
subMenuItem.add(subLink);
continue;
}
// final WebMarkupContainer subsubMenuContainer = new WebMarkupContainer("subsubMenu");
// subMenuItem.add(subsubMenuContainer);
// if (subMenuEntry.hasSubMenuEntries() == false) {
// subsubMenuContainer.setVisible(false);
// continue;
// }
// final RepeatingView subsubMenuRepeater = new RepeatingView("subsubMenuRepeater");
// subsubMenuContainer.add(subsubMenuRepeater);
for (final MenuEntry subsubMenuEntry : subMenuEntry.getSubMenuEntries()) {
// Now we add the next menu entry to the sub menu:
final WebMarkupContainer subMenuItem = new WebMarkupContainer(subMenuRepeater.newChildId());
subMenuRepeater.add(subMenuItem);
// Subsubmenu entries aren't yet supported, show only the sub entries without children, otherwise only the children are
// displayed.
final AbstractLink subLink = getMenuEntryLink(subsubMenuEntry, true);
if (subLink == null) {
subMenuItem.setVisible(false);
continue;
}
subMenuItem.add(subLink);
// final WebMarkupContainer subsubMenuItem = new WebMarkupContainer(subsubMenuRepeater.newChildId());
// subsubMenuRepeater.add(subsubMenuItem);
// final AbstractLink subsubLink = getMenuEntryLink(subsubMenuEntry, subsubMenuItem);
// subsubMenuItem.add(subsubLink);
}
}
}
}
}
private void addBookmarkDialog()
{
final AbstractSecuredPage parentPage = (AbstractSecuredPage) getPage();
bookmarkDialog = new BookmarkDialog(parentPage.newModalDialogId());
bookmarkDialog.setOutputMarkupId(true);
parentPage.add(bookmarkDialog);
bookmarkDialog.init();
}
@SuppressWarnings("serial")
private class BookmarkDialog extends ModalDialog
{
/**
* @param id
*/
public BookmarkDialog(final String id)
{
super(id);
}
@Override
public void init()
{
setTitle(getString("bookmark.title"));
init(new Form<String>(getFormId()));
gridBuilder.newFormHeading(""); // Otherwise it's empty and an IllegalArgumentException is thrown.
}
private BookmarkDialog redraw()
{
clearContent();
final AbstractSecuredPage page = (AbstractSecuredPage) NavTopPanel.this.getPage();
{
final FieldsetPanel fs = gridBuilder.newFieldset(getString("bookmark.directPageLink")).setLabelSide(false);
final TextArea<String> textArea = new TextArea<String>(fs.getTextAreaId(), new Model<String>(page.getPageAsLink()));
fs.add(textArea);
textArea.add(AttributeModifier.replace("onClick", "$(this).select();"));
}
final PageParameters params = page.getBookmarkableInitialParameters();
if (params.isEmpty() == false) {
final FieldsetPanel fs = gridBuilder.newFieldset(getString(page.getTitleKey4BookmarkableInitialParameters())).setLabelSide(false);
final TextArea<String> textArea = new TextArea<String>(fs.getTextAreaId(), new Model<String>(page.getPageAsLink(params)));
fs.add(textArea);
textArea.add(AttributeModifier.replace("onClick", "$(this).select();"));
}
return this;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_6 |
crossvul-java_data_good_5842_1 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.lang.Bytes;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.FileUploadPanel;
public class SetupImportForm extends AbstractForm<SetupImportForm, SetupPage>
{
private static final long serialVersionUID = -277853572580468505L;
protected FileUploadField fileUploadField;
protected String filename;
/**
* Cross site request forgery token.
*/
private final CsrfTokenHandler csrfTokenHandler;
public SetupImportForm(final SetupPage parentPage)
{
super(parentPage, "importform");
initUpload(Bytes.megabytes(100));
csrfTokenHandler = new CsrfTokenHandler(this);
}
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
final GridBuilder gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newFormHeading(getString("import"));
{
// Upload dump file
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.setup.dumpFile"));
fileUploadField = new FileUploadField(FileUploadPanel.WICKET_ID);
fs.add(new FileUploadPanel(fs.newChildId(), fileUploadField));
}
final RepeatingView actionButtons = new RepeatingView("buttons");
add(actionButtons);
{
final Button importButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("import")) {
@Override
public final void onSubmit()
{
parentPage.upload();
}
};
final SingleButtonPanel importButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), importButton, getString("import"),
SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(importButtonPanel);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_1 |
crossvul-java_data_bad_2031_5 | package org.jolokia.restrictor;
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* A Restrictor is used to restrict the access to MBeans based on
* various parameters.
*
* @author roland
* @since Jul 28, 2009
*/
public interface Restrictor {
/**
* Check whether the HTTP method with which the request
* was sent is allowed.
*
* @param pMethod method to check
* @return true if there is no restriction on the method with which the request
* was sent, false otherwise
*/
boolean isHttpMethodAllowed(HttpMethod pMethod);
/**
* Check whether the provided command type is allowed in principal
*
* @param pType type to check
* @return true, if the type is allowed, false otherwise
*/
boolean isTypeAllowed(RequestType pType);
/**
* Check whether reading of an attribute is allowed
*
* @param pName MBean name
* @param pAttribute attribute to check
* @return true if access is allowed
*/
boolean isAttributeReadAllowed(ObjectName pName,String pAttribute);
/**
* Check whether writing of an attribute is allowed
*
* @param pName MBean name
* @param pAttribute attribute to check
* @return true if access is allowed
*/
boolean isAttributeWriteAllowed(ObjectName pName,String pAttribute);
/**
* Check whether execution of an operation is allowed
*
* @param pName MBean name
* @param pOperation attribute to check
* @return true if access is allowed
*/
boolean isOperationAllowed(ObjectName pName,String pOperation);
/**
* Check whether access from the connected client is allowed. If at least
* one of the given parameters matches, then this method returns true.
*
* @return true is access is allowed
* @param pHostOrAddress one or more host or address names
*/
boolean isRemoteAccessAllowed(String ... pHostOrAddress);
/**
* Check whether cross browser access via CORS is allowed. See the
* <a href="https://developer.mozilla.org/en/http_access_control">CORS</a> specification
* for details
*
* @param pOrigin the "Origin:" URL provided within the request
* @return true if this cross browser request allowed, false otherwise
*/
boolean isCorsAccessAllowed(String pOrigin);
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_5 |
crossvul-java_data_good_2031_9 | package org.jolokia.http;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.management.*;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import org.jolokia.config.Configuration;
import org.jolokia.backend.BackendManager;
import org.jolokia.request.JmxReadRequest;
import org.jolokia.request.JmxRequest;
import org.jolokia.test.util.HttpTestUtil;
import org.jolokia.util.LogHandler;
import org.jolokia.util.RequestType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.testng.annotations.*;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 31.08.11
*/
public class HttpRequestHandlerTest {
private BackendManager backend;
private HttpRequestHandler handler;
@BeforeMethod
public void setup() {
backend = createMock(BackendManager.class);
expect(backend.isDebug()).andReturn(true).anyTimes();
handler = new HttpRequestHandler(new Configuration(),backend, createDummyLogHandler());
}
@AfterMethod
public void tearDown() {
verify(backend);
}
@Test
public void accessAllowed() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
replay(backend);
handler.checkAccess("localhost", "127.0.0.1",null);
}
@Test(expectedExceptions = { SecurityException.class })
public void accessDenied() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false);
replay(backend);
handler.checkAccess("localhost", "127.0.0.1",null);
}
@Test(expectedExceptions = { SecurityException.class })
public void accessDeniedViaOrigin() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
expect(backend.isOriginAllowed("www.jolokia.org",true)).andReturn(false);
replay(backend);
handler.checkAccess("localhost", "127.0.0.1","www.jolokia.org");
}
@Test
public void get() throws InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp);
replay(backend);
JSONObject response = (JSONObject) handler.handleGetRequest("/jolokia", HttpTestUtil.HEAP_MEMORY_GET_REQUEST, null);
assertTrue(response == resp);
}
@Test
public void getWithDoubleSlashes() throws MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(eqReadRequest("read", "bla:type=s/lash/", "attribute"))).andReturn(resp);
replay(backend);
JSONObject response = (JSONObject) handler.handleGetRequest("/read/bla%3Atype%3Ds!/lash!//attribute",
"/read/bla:type=s!/lash!/Ok",null);
assertTrue(response == resp);
}
private JmxRequest eqReadRequest(String pType, final String pMBean, final String pAttribute) {
EasyMock.reportMatcher(new IArgumentMatcher() {
public boolean matches(Object argument) {
try {
JmxReadRequest req = (JmxReadRequest) argument;
return req.getType() == RequestType.READ &&
new ObjectName(pMBean).equals(req.getObjectName()) &&
pAttribute.equals(req.getAttributeName());
} catch (MalformedObjectNameException e) {
return false;
}
}
public void appendTo(StringBuffer buffer) {
buffer.append("eqReadRequest(mbean = \"");
buffer.append(pMBean);
buffer.append("\", attribute = \"");
buffer.append(pAttribute);
buffer.append("\")");
}
});
return null;
}
@Test
public void singlePost() throws IOException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp);
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream(HttpTestUtil.HEAP_MEMORY_POST_REQUEST);
JSONObject response = (JSONObject) handler.handlePostRequest("/jolokia",is,"utf-8",null);
assertTrue(response == resp);
}
@Test
public void doublePost() throws IOException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp).times(2);
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("[" + HttpTestUtil.HEAP_MEMORY_POST_REQUEST + "," + HttpTestUtil.HEAP_MEMORY_POST_REQUEST + "]");
JSONArray response = (JSONArray) handler.handlePostRequest("/jolokia", is, "utf-8", null);
assertEquals(response.size(),2);
assertTrue(response.get(0) == resp);
assertTrue(response.get(1) == resp);
}
@Test
public void preflightCheck() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isOriginAllowed(origin,false)).andReturn(true);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
}
@Test
public void preflightCheckNegative() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isOriginAllowed(origin,false)).andReturn(false);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertNull(ret.get("Access-Control-Allow-Origin"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void invalidJson() throws IOException {
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("{ bla;");
handler.handlePostRequest("/jolokia",is,"utf-8",null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void invalidJson2() throws IOException {
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("12");
handler.handlePostRequest("/jolokia",is,"utf-8",null);
}
@Test
public void requestErrorHandling() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Object[] exceptions = new Object[] {
new ReflectionException(new NullPointerException()), 404,500,
new InstanceNotFoundException(), 404, 500,
new MBeanException(new NullPointerException()), 500, 500,
new AttributeNotFoundException(), 404, 500,
new UnsupportedOperationException(), 500, 500,
new IOException(), 500, 500,
new IllegalArgumentException(), 400, 400,
new SecurityException(),403, 403,
new RuntimeMBeanException(new NullPointerException()), 500, 500
};
for (int i = 0; i < exceptions.length; i += 3) {
Exception e = (Exception) exceptions[i];
reset(backend);
expect(backend.isDebug()).andReturn(true).anyTimes();
backend.error(find("" + exceptions[i + 1]), EasyMock.<Throwable>anyObject());
backend.error(find("" + exceptions[i + 2]), EasyMock.<Throwable>anyObject());
expect(backend.handleRequest(EasyMock.<JmxRequest>anyObject())).andThrow(e);
replay(backend);
JSONObject resp = (JSONObject) handler.handleGetRequest("/jolokia",
"/read/java.lang:type=Memory/HeapMemoryUsage",null);
assertEquals(resp.get("status"),exceptions[i+1]);
resp = handler.handleThrowable(e);
assertEquals(resp.get("status"),exceptions[i+2],e.getClass().getName());
}
}
// ======================================================================================================
private LogHandler createDummyLogHandler() {
return new LogHandler() {
public void debug(String message) {
}
public void info(String message) {
}
public void error(String message, Throwable t) {
}
};
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_9 |
crossvul-java_data_good_2031_10 | package org.jolokia.restrictor;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.InputStream;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
/**
* @author roland
* @since Jul 29, 2009
*/
public class PolicyBasedRestrictorTest {
@Test
public void basics() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"Verbose"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"Verbose"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"),"gc"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Threading"),"gc"));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.POST));
assertFalse(restrictor.isHttpMethodAllowed(HttpMethod.GET));
}
@Test
public void restrictIp() {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
String ips[][] = {
{ "11.0.18.32", "true" },
{ "planck", "true" },
{ "heisenberg", "false" },
{ "10.0.11.125", "true" },
{ "10.0.11.126", "false" },
{ "11.1.18.32", "false" },
{ "192.168.15.3", "true" },
{ "192.168.15.8", "true" },
{ "192.168.16.3", "false" }
};
for (String check[] : ips) {
String res = restrictor.isRemoteAccessAllowed(check[0]) ? "true" : "false";
assertEquals("Ip " + check[0] + " is " +
(check[1].equals("false") ? "not " : "") +
"allowed",check[1],res);
}
}
@Test
public void patterns() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config,name=Bla"),"Debug"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("jolokia:type=Threading"),"gc"));
// No hosts set.
assertTrue(restrictor.isRemoteAccessAllowed("10.0.1.125"));
}
@Test
public void noRestrictions() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config,name=Bla"),"Debug"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("jolokia:type=Threading"),"gc"));
assertTrue(restrictor.isTypeAllowed(RequestType.READ));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.POST));
}
@Test
public void deny() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample4.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"HeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"),"NonHeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"),"BlaUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config"),"Debug"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"),"gc"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"),"xavier"));
}
@Test
public void allow() throws MalformedObjectNameException {
InputStream is = getClass().getResourceAsStream("/access-sample5.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
assertFalse(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "BlaUsage"));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config"), "Debug"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "gc"));
assertFalse(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "xavier"));
}
@Test
public void illegalXml() {
InputStream is = getClass().getResourceAsStream("/illegal1.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
//ok
}
try {
new PolicyRestrictor(null);
fail("No file given");
} catch (SecurityException exp) {
// ok
}
}
@Test
public void noName() {
InputStream is = getClass().getResourceAsStream("/illegal2.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
}
}
@Test
public void invalidTag() {
InputStream is = getClass().getResourceAsStream("/illegal3.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
assertTrue(exp.getMessage().contains("attribute"));
assertTrue(exp.getMessage().contains("operation"));
assertTrue(exp.getMessage().contains("bla"));
}
}
@Test
public void doubleName() {
InputStream is = getClass().getResourceAsStream("/illegal4.xml");
try {
PolicyRestrictor restrictor = new PolicyRestrictor(is);
fail("Could parse illegal file");
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("name"));
}
}
@Test
public void httpMethod() {
InputStream is = getClass().getResourceAsStream("/method.xml");
PolicyRestrictor res = new PolicyRestrictor(is);
assertTrue(res.isHttpMethodAllowed(HttpMethod.GET));
assertTrue(res.isHttpMethodAllowed(HttpMethod.POST));
}
@Test
public void illegalHttpMethod() {
InputStream is = getClass().getResourceAsStream("/illegal5.xml");
try {
new PolicyRestrictor(is);
fail();
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("BLA"));
}
}
@Test
public void illegalHttpMethodTag() {
InputStream is = getClass().getResourceAsStream("/illegal6.xml");
try {
new PolicyRestrictor(is);
fail();
} catch (SecurityException exp) {
assertTrue(exp.getMessage().contains("method"));
assertTrue(exp.getMessage().contains("blubber"));
}
}
@Test
public void cors() {
InputStream is = getClass().getResourceAsStream("/allow-origin4.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
for (boolean strict : new boolean[] {true, false}) {
assertTrue(restrictor.isOriginAllowed("http://bla.com", strict));
assertFalse(restrictor.isOriginAllowed("http://www.jolokia.org", strict));
assertTrue(restrictor.isOriginAllowed("https://www.consol.de", strict));
}
}
@Test
public void corsStrictCheckingOff() {
InputStream is = getClass().getResourceAsStream("/allow-origin1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
// Allways true since we want a strict check but strict checking is off.
assertTrue(restrictor.isOriginAllowed("http://bla.com", true));
assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", true));
assertTrue(restrictor.isOriginAllowed("https://www.consol.de", true));
}
@Test
public void corsWildCard() {
InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
assertTrue(restrictor.isOriginAllowed("http://www.consol.de", false));
}
@Test
public void corsEmpty() {
InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
assertTrue(restrictor.isOriginAllowed("http://www.consol.de", false));
}
@Test
public void corsNoTags() {
InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
assertTrue(restrictor.isOriginAllowed("https://www.consol.de", false));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_10 |
crossvul-java_data_bad_5842_1 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.lang.Bytes;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.FileUploadPanel;
public class SetupImportForm extends AbstractForm<SetupImportForm, SetupPage>
{
private static final long serialVersionUID = -277853572580468505L;
protected FileUploadField fileUploadField;
protected String filename;
public SetupImportForm(final SetupPage parentPage)
{
super(parentPage, "importform");
initUpload(Bytes.megabytes(100));
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
final GridBuilder gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newFormHeading(getString("import"));
{
// Upload dump file
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.setup.dumpFile"));
fileUploadField = new FileUploadField(FileUploadPanel.WICKET_ID);
fs.add(new FileUploadPanel(fs.newChildId(), fileUploadField));
}
final RepeatingView actionButtons = new RepeatingView("buttons");
add(actionButtons);
{
final Button importButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("import")) {
@Override
public final void onSubmit()
{
parentPage.upload();
}
};
final SingleButtonPanel importButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), importButton, getString("import"),
SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(importButtonPanel);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_1 |
crossvul-java_data_bad_2031_8 | package org.jolokia.http;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.io.*;
import java.net.SocketException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jolokia.backend.TestDetector;
import org.jolokia.config.ConfigKey;
import org.jolokia.discovery.JolokiaDiscovery;
import org.jolokia.restrictor.AllowAllRestrictor;
import org.jolokia.test.util.HttpTestUtil;
import org.jolokia.util.LogHandler;
import org.jolokia.util.NetworkUtil;
import org.json.simple.JSONObject;
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 30.08.11
*/
public class AgentServletTest {
private ServletContext context;
private ServletConfig config;
private HttpServletRequest request;
private HttpServletResponse response;
private AgentServlet servlet;
@Test
public void simpleInit() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(null, null,"No access restrictor found", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithAcessRestriction() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "classpath:/access-sample1.xml"},
null,
"Using access restrictor.*access-sample1.xml", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithInvalidPolicyFile() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "file:///blablub.xml"},
null,
"Error.*blablub.xml.*Denying", FileNotFoundException.class);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void configWithOverWrite() throws ServletException {
servlet = new AgentServlet();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
initConfigMocks(new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/jmx4perl",ConfigKey.MAX_DEPTH.getKeyValue(),"10"},
new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/j0l0k14",ConfigKey.MAX_OBJECTS.getKeyValue(),"20",
ConfigKey.CALLBACK.getKeyValue(),"callback is a request option, must be empty here"},
null,null);
replay(config, context,request,response);
servlet.init(config);
servlet.destroy();
org.jolokia.config.Configuration cfg = servlet.initConfig(config);
assertEquals(cfg.get(ConfigKey.AGENT_CONTEXT), "/j0l0k14");
assertEquals(cfg.get(ConfigKey.MAX_DEPTH), "10");
assertEquals(cfg.get(ConfigKey.MAX_OBJECTS), "20");
assertNull(cfg.get(ConfigKey.CALLBACK));
assertNull(cfg.get(ConfigKey.DETECTOR_OPTIONS));
}
@Test
public void initWithcustomAccessRestrictor() throws ServletException {
prepareStandardInitialisation();
servlet.destroy();
}
@Test
public void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
}
@Test
public void initWithAgentDiscoveryAndGivenUrl() throws ServletException, IOException, InterruptedException {
checkMulticastAvailable();
String url = "http://localhost:8080/jolokia";
prepareStandardInitialisation(ConfigKey.DISCOVERY_AGENT_URL.getKeyValue(), url);
// Wait listening thread to warm up
Thread.sleep(1000);
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgentsWithTimeout(500);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
return;
}
}
fail("No agent found");
} finally {
servlet.destroy();
}
}
@Test
public void initWithAgentDiscoveryAndUrlLookup() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
// At least one doesnt have an URL (remove this part if a way could be found for getting
// to the URL
for (JSONObject json : in) {
if (json.get("url") == null) {
return;
}
}
fail("Every message has an URL");
} finally {
servlet.destroy();
}
}
private void checkMulticastAvailable() throws SocketException {
if (!NetworkUtil.isMulticastSupported()) {
throw new SkipException("No multicast interface found, skipping test ");
}
}
@Test
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
String url = "http://pirx:9876/jolokia";
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn(buf.toString());
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
}
public static class CustomLogHandler implements LogHandler {
private static int infoCount = 0;
public CustomLogHandler() {
infoCount = 0;
}
public void debug(String message) {
}
public void info(String message) {
infoCount++;
}
public void error(String message, Throwable t) {
}
}
@Test
public void simpleGet() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
Vector params = new Vector();
params.add("debug");
expect(request.getParameterNames()).andReturn(params.elements());
expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request,response);
servlet.doGet(request,response);
servlet.destroy();
}
@Test
public void simplePost() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter responseWriter = initRequestResponseMocks();
expect(request.getCharacterEncoding()).andReturn("utf-8");
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
preparePostRequest(HttpTestUtil.HEAP_MEMORY_POST_REQUEST);
replay(request, response);
servlet.doPost(request, response);
assertTrue(responseWriter.toString().contains("used"));
servlet.destroy();
}
@Test
public void unknownMethodWhenSettingContentType() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
expectLastCall().andThrow(new NoSuchMethodError());
response.setContentType("text/plain; charset=utf-8");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void corsPreflightCheck() throws ServletException, IOException {
checkCorsOriginPreflight("http://bla.com", "http://bla.com");
}
@Test
public void corsPreflightCheckWithNullOrigin() throws ServletException, IOException {
checkCorsOriginPreflight("null", "*");
}
private void checkCorsOriginPreflight(String in, String out) throws ServletException, IOException {
prepareStandardInitialisation();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getHeader("Access-Control-Request-Headers")).andReturn(null);
response.setHeader(eq("Access-Control-Allow-Max-Age"), (String) anyObject());
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials", "true");
replay(request, response);
servlet.doOptions(request, response);
servlet.destroy();
}
@Test
public void corsHeaderGetCheck() throws ServletException, IOException {
checkCorsGetOrigin("http://bla.com","http://bla.com");
}
@Test
public void corsHeaderGetCheckWithNullOrigin() throws ServletException, IOException {
checkCorsGetOrigin("null","*");
}
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
}
private void setNoCacheHeaders(HttpServletResponse pResp) {
pResp.setHeader("Cache-Control", "no-cache");
pResp.setHeader("Pragma","no-cache");
pResp.setDateHeader(eq("Date"),anyLong());
pResp.setDateHeader(eq("Expires"),anyLong());
}
@Test
public void withCallback() throws IOException, ServletException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
"myCallback",
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
response.setContentType("text/javascript");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().matches("^myCallback\\(.*\\);$"));
servlet.destroy();
}
@Test
public void withException() throws ServletException, IOException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(null, null,"Error 500", IllegalStateException.class);
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andThrow(new IllegalStateException());
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
String resp = sw.toString();
assertTrue(resp.contains("error_type"));
assertTrue(resp.contains("IllegalStateException"));
assertTrue(resp.matches(".*status.*500.*"));
servlet.destroy();
verify(config, context, request, response);
}
@Test
public void debug() throws IOException, ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null);
context.log(find("URI:"));
context.log(find("Path-Info:"));
context.log(find("Request:"));
context.log(find("time:"));
context.log(find("Response:"));
context.log(find("TestDetector"),isA(RuntimeException.class));
expectLastCall().anyTimes();
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@BeforeMethod
void resetTestDetector() {
TestDetector.reset();
}
//@AfterMethod
public void verifyMocks() {
verify(config, context, request, response);
}
// ============================================================================================
private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) {
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];
params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();
params[params.length - 1] = "true";
HttpTestUtil.prepareServletConfigMock(config,params);
HttpTestUtil.prepareServletContextMock(context, pContextParams);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
if (pExceptionClass != null) {
context.log(find(pLogRegexp),isA(pExceptionClass));
} else {
if (pLogRegexp != null) {
context.log(find(pLogRegexp));
} else {
context.log((String) anyObject());
}
}
context.log((String) anyObject());
expectLastCall().anyTimes();
context.log(find("TestDetector"),isA(RuntimeException.class));
}
private StringWriter initRequestResponseMocks() throws IOException {
return initRequestResponseMocks(
getStandardRequestSetup(),
getStandardResponseSetup());
}
private StringWriter initRequestResponseMocks(Runnable requestSetup,Runnable responseSetup) throws IOException {
return initRequestResponseMocks(null,requestSetup,responseSetup);
}
private StringWriter initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException {
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
setNoCacheHeaders(response);
expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback);
requestSetup.run();
responseSetup.run();
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
expect(response.getWriter()).andReturn(writer);
return sw;
}
private void preparePostRequest(String pReq) throws IOException {
ServletInputStream is = HttpTestUtil.createServletInputStream(pReq);
expect(request.getInputStream()).andReturn(is);
}
private void prepareStandardInitialisation(String ... params) throws ServletException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(params.length > 0 ? params : null, null,"custom access", null);
replay(config, context);
servlet.init(config);
}
private Runnable getStandardResponseSetup() {
return new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
};
}
private Runnable getStandardRequestSetup() {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
};
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_8 |
crossvul-java_data_good_5842_8 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.dialog;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.projectforge.web.core.NavTopPanel;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.MyComponentsRepeater;
import de.micromata.wicket.ajax.AjaxCallback;
import de.micromata.wicket.ajax.AjaxFormSubmitCallback;
/**
* Base component for the ProjectForge modal dialogs.<br/>
* This dialog is modal.<br/>
*
* @author Johannes Unterstein (j.unterstein@micromata.de)
* @author Kai Reinhard (k.reinhard@micromata.de)
*
*/
public abstract class ModalDialog extends Panel
{
private static final long serialVersionUID = 4235521713603821639L;
protected GridBuilder gridBuilder;
protected final WebMarkupContainer mainContainer, mainSubContainer, gridContentContainer, buttonBarContainer;
private boolean escapeKeyEnabled = true;
private String closeButtonLabel;
private SingleButtonPanel closeButtonPanel;
private boolean showCancelButton;
private boolean bigWindow;
private boolean draggable = true;
private Boolean resizable;
private boolean lazyBinding;
private WebMarkupContainer titleContainer;
private Label titleLabel;
protected Form< ? > form;
protected FeedbackPanel formFeedback;
/**
* If true, a GridBuilder is automatically available.
*/
protected boolean autoGenerateGridBuilder = true;
/**
* List to create action buttons in the desired order before creating the RepeatingView.
*/
protected MyComponentsRepeater<Component> actionButtons;
/**
* Cross site request forgery token.
*/
protected CsrfTokenHandler csrfTokenHandler;
/**
* @param id
*/
public ModalDialog(final String id)
{
super(id);
actionButtons = new MyComponentsRepeater<Component>("actionButtons");
mainContainer = new WebMarkupContainer("mainContainer");
add(mainContainer.setOutputMarkupId(true));
mainContainer.add(mainSubContainer = new WebMarkupContainer("mainSubContainer"));
gridContentContainer = new WebMarkupContainer("gridContent");
gridContentContainer.setOutputMarkupId(true);
buttonBarContainer = new WebMarkupContainer("buttonBar");
buttonBarContainer.setOutputMarkupId(true);
}
/**
* @see org.apache.wicket.Component#onInitialize()
*/
@Override
protected void onInitialize()
{
super.onInitialize();
if (bigWindow == true) {
mainContainer.add(AttributeModifier.append("class", "big-modal"));
}
}
/**
* Sets also draggable to false. Appends css class big-modal.
*/
public ModalDialog setBigWindow()
{
bigWindow = true;
draggable = false;
return this;
}
/**
* Only the div panel of the modal dialog is rendered without buttons and content. Default is false.
* @return this for chaining.
*/
public ModalDialog setLazyBinding()
{
this.lazyBinding = true;
mainSubContainer.setVisible(false);
return this;
}
public void bind(final AjaxRequestTarget target)
{
actionButtons.render();
mainSubContainer.setVisible(true);
target.appendJavaScript(getJavaScriptAction());
}
/**
* @return true if no lazy binding was used or bind() was already called.
*/
public boolean isBound()
{
return mainSubContainer.isVisible();
}
/**
* @param draggable the draggable to set (default is true).
* @return this for chaining.
*/
public ModalDialog setDraggable(final boolean draggable)
{
this.draggable = draggable;
return this;
}
/**
* @param resizable the resizable to set (default is true for bigWindows, otherwise false).
* @return this for chaining.
*/
public ModalDialog setResizable(final boolean resizable)
{
this.resizable = resizable;
return this;
}
/**
* Display the cancel button.
* @return this for chaining.
*/
public ModalDialog setShowCancelButton()
{
this.showCancelButton = true;
return this;
}
/**
* @param escapeKeyEnabled the keyboard to set (default is true).
* @return this for chaining.
*/
public ModalDialog setEscapeKeyEnabled(final boolean escapeKeyEnabled)
{
this.escapeKeyEnabled = escapeKeyEnabled;
return this;
}
/**
* Close is used as default:
* @param closeButtonLabel the closeButtonLabel to set
* @return this for chaining.
*/
public ModalDialog setCloseButtonLabel(final String closeButtonLabel)
{
this.closeButtonLabel = closeButtonLabel;
return this;
}
/**
* Should be called directly after {@link #init()}.
* @param tooltipTitle
* @param tooltipContent
* @see WicketUtils#addTooltip(Component, IModel, IModel)
*/
public ModalDialog setCloseButtonTooltip(final IModel<String> tooltipTitle, final IModel<String> tooltipContent)
{
WicketUtils.addTooltip(this.closeButtonPanel.getButton(), tooltipTitle, tooltipContent);
return this;
}
@SuppressWarnings("serial")
public ModalDialog wantsNotificationOnClose()
{
mainContainer.add(new AjaxEventBehavior("hidden") {
@Override
protected void onEvent(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
handleCloseEvent(target);
}
});
return this;
}
public ModalDialog addAjaxEventBehavior(final AjaxEventBehavior behavior)
{
mainContainer.add(behavior);
return this;
}
public String getMainContainerMarkupId()
{
return mainContainer.getMarkupId(true);
}
@Override
public void renderHead(final IHeaderResponse response)
{
super.renderHead(response);
if (lazyBinding == false) {
final String script = getJavaScriptAction();
response.render(OnDomReadyHeaderItem.forScript(script));
}
}
private String getJavaScriptAction()
{
final StringBuffer script = new StringBuffer();
script.append("$('#").append(getMainContainerMarkupId()).append("').modal({keyboard: ").append(escapeKeyEnabled)
.append(", show: false });");
final boolean isResizable = (resizable == null && bigWindow == true) || Boolean.TRUE.equals(resizable) == true;
if (draggable == true || isResizable == true) {
script.append(" $('#").append(getMainContainerMarkupId()).append("')");
}
if (draggable == true) {
script.append(".draggable()");
}
if (isResizable) {
script.append(".resizable({ alsoResize: '#")
.append(getMainContainerMarkupId())
// max-height of .modal-body is 600px, need to enlarge this setting for resizing.
.append(
", .modal-body', resize: function( event, ui ) {$('.modal-body').css('max-height', '4000px');}, minWidth: 300, minHeight: 200 })");
}
return script.toString();
}
public ModalDialog open(final AjaxRequestTarget target)
{
target.appendJavaScript("$('#" + getMainContainerMarkupId() + "').modal('show');");
return this;
}
public void close(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
target.appendJavaScript("$('#" + getMainContainerMarkupId() + "').modal('hide');");
}
/**
* Add the content to the AjaxRequestTarget if the content is changed.
* @param target
* @return this for chaining.
*/
public ModalDialog addContent(final AjaxRequestTarget target)
{
target.add(gridContentContainer);
return this;
}
/**
* Add the button bar to the AjaxRequestTarget if the buttons or their visibility are changed.
* @param target
* @return this for chaining.
*/
public ModalDialog addButtonBar(final AjaxRequestTarget target)
{
target.add(buttonBarContainer);
return this;
}
/**
* @param target
* @return this for chaining.
*/
public ModalDialog addTitleLabel(final AjaxRequestTarget target)
{
target.add(titleLabel);
return this;
}
public abstract void init();
/**
* @param title
* @return this for chaining.
*/
public ModalDialog setTitle(final String title)
{
return setTitle(Model.of(title));
}
/**
* @param title
* @return this for chaining.
*/
public ModalDialog setTitle(final IModel<String> title)
{
titleContainer = new WebMarkupContainer("titleContainer");
mainSubContainer.add(titleContainer.setOutputMarkupId(true));
titleContainer.add(titleLabel = new Label("titleText", title));
titleLabel.setOutputMarkupId(true);
return this;
}
/**
* The gridContentContainer is cleared (all child elements are removed). This is useful for Ajax dialogs with dynamic content (see
* {@link NavTopPanel} for an example).
* @return
*/
public ModalDialog clearContent()
{
gridContentContainer.removeAll();
if (autoGenerateGridBuilder == true) {
gridBuilder = new GridBuilder(gridContentContainer, "flowform");
}
initFeedback(gridContentContainer);
return this;
}
@SuppressWarnings("serial")
protected void init(final Form< ? > form)
{
this.form = form;
csrfTokenHandler = new CsrfTokenHandler(form);
mainSubContainer.add(form);
form.add(gridContentContainer);
form.add(buttonBarContainer);
if (showCancelButton == true) {
final SingleButtonPanel cancelButton = appendNewAjaxActionButton(new AjaxCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
onCancelButtonSubmit(target);
close(target);
}
}, getString("cancel"), SingleButtonPanel.CANCEL);
cancelButton.getButton().setDefaultFormProcessing(false);
}
closeButtonPanel = appendNewAjaxActionButton(new AjaxFormSubmitCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
if (onCloseButtonSubmit(target)) {
close(target);
}
}
@Override
public void onError(final AjaxRequestTarget target, final Form< ? > form)
{
csrfTokenHandler.onSubmit();
ModalDialog.this.onError(target, form);
}
}, closeButtonLabel != null ? closeButtonLabel : getString("close"), SingleButtonPanel.NORMAL);
buttonBarContainer.add(actionButtons.getRepeatingView());
form.setDefaultButton(closeButtonPanel.getButton());
if (autoGenerateGridBuilder == true) {
gridBuilder = new GridBuilder(gridContentContainer, "flowform");
}
initFeedback(gridContentContainer);
}
private void initFeedback(final WebMarkupContainer container)
{
if (formFeedback == null) {
formFeedback = new FeedbackPanel("formFeedback", new ComponentFeedbackMessageFilter(form));
formFeedback.setOutputMarkupId(true);
formFeedback.setOutputMarkupPlaceholderTag(true);
}
container.add(formFeedback);
}
protected void ajaxError(final String error, final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
form.error(error);
target.add(formFeedback);
}
/**
* Called if {@link #wantsNotificationOnClose()} was chosen and the dialog is closed (by pressing esc, clicking outside or clicking the
* upper right cross).
* @param target
*/
protected void handleCloseEvent(final AjaxRequestTarget target)
{
csrfTokenHandler.onSubmit();
}
/**
* Called if user hit the cancel button.
* @param target
*/
protected void onCancelButtonSubmit(final AjaxRequestTarget target)
{
}
/**
* Called if user hit the close button.
*
* @param target
*
* @return true if the dialog can be close, false if errors occured.
*/
protected boolean onCloseButtonSubmit(final AjaxRequestTarget target)
{
return true;
}
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
}
/**
* @see org.apache.wicket.Component#onBeforeRender()
*/
@Override
protected void onBeforeRender()
{
super.onBeforeRender();
if (lazyBinding == false) {
actionButtons.render();
}
}
public String getFormId()
{
return "form";
}
public SingleButtonPanel appendNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
final SingleButtonPanel result = addNewAjaxActionButton(ajaxCallback, label, classnames);
this.actionButtons.add(result);
return result;
}
public SingleButtonPanel prependNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
return insertNewAjaxActionButton(ajaxCallback, 0, label, classnames);
}
/**
* @param ajaxCallback
* @param position 0 is the first position.
* @param label
* @param classnames
* @return
*/
public SingleButtonPanel insertNewAjaxActionButton(final AjaxCallback ajaxCallback, final int position, final String label,
final String... classnames)
{
final SingleButtonPanel result = addNewAjaxActionButton(ajaxCallback, label, classnames);
this.actionButtons.add(position, result);
return result;
}
private SingleButtonPanel addNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
final AjaxButton button = new AjaxButton("button", form) {
private static final long serialVersionUID = -5306532706450731336L;
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
csrfTokenHandler.onSubmit();
ajaxCallback.callback(target);
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
if (ajaxCallback instanceof AjaxFormSubmitCallback) {
((AjaxFormSubmitCallback) ajaxCallback).onError(target, form);
}
}
};
final SingleButtonPanel buttonPanel = new SingleButtonPanel(this.actionButtons.newChildId(), button, label, classnames);
buttonPanel.add(button);
return buttonPanel;
}
/**
* @return the mainContainer
*/
public WebMarkupContainer getMainContainer()
{
return mainContainer;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_8 |
crossvul-java_data_bad_5842_3 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import java.util.SortedSet;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.projectforge.Version;
import org.projectforge.continuousdb.UpdateEntry;
import org.projectforge.continuousdb.UpdatePreCheckStatus;
import org.projectforge.web.HtmlHelper;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.CheckBoxPanel;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.MyComponentsRepeater;
public class SystemUpdateForm extends AbstractForm<SystemUpdateForm, SystemUpdatePage>
{
private static final long serialVersionUID = 2492737003121592489L;
protected WebMarkupContainer scripts;
public boolean showOldUpdateScripts;
private GridBuilder gridBuilder;
/**
* List to create content menu in the desired order before creating the RepeatingView.
*/
protected MyComponentsRepeater<SingleButtonPanel> actionButtons;
public SystemUpdateForm(final SystemUpdatePage parentPage)
{
super(parentPage);
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newGridPanel();
{
final FieldsetPanel fs = gridBuilder.newFieldset("Show all");
fs.add(new CheckBoxPanel(fs.newChildId(), new PropertyModel<Boolean>(this, "showOldUpdateScripts"), null, true) {
/**
* @see org.projectforge.web.wicket.flowlayout.CheckBoxPanel#onSelectionChanged(java.lang.Boolean)
*/
@Override
protected void onSelectionChanged(final Boolean newSelection)
{
parentPage.refresh();
}
});
}
scripts = new WebMarkupContainer("scripts");
add(scripts);
updateEntryRows();
actionButtons = new MyComponentsRepeater<SingleButtonPanel>("buttons");
add(actionButtons.getRepeatingView());
{
final Button refreshButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("refresh")) {
@Override
public final void onSubmit()
{
parentPage.refresh();
}
};
final SingleButtonPanel refreshButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), refreshButton, "refresh",
SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(refreshButtonPanel);
setDefaultButton(refreshButton);
}
}
@SuppressWarnings("serial")
protected void updateEntryRows()
{
scripts.removeAll();
final RepeatingView scriptRows = new RepeatingView("scriptRows");
scripts.add(scriptRows);
final SortedSet<UpdateEntry> updateEntries = parentPage.myDatabaseUpdater.getSystemUpdater().getUpdateEntries();
if (updateEntries == null) {
return;
}
boolean odd = true;
for (final UpdateEntry updateEntry : updateEntries) {
if (showOldUpdateScripts == false && updateEntry.getPreCheckStatus() == UpdatePreCheckStatus.ALREADY_UPDATED) {
continue;
}
final Version version = updateEntry.getVersion();
final WebMarkupContainer item = new WebMarkupContainer(scriptRows.newChildId());
scriptRows.add(item);
if (odd == true) {
item.add(AttributeModifier.append("class", "odd"));
} else {
item.add(AttributeModifier.append("class", "even"));
}
odd = !odd;
item.add(new Label("regionId", updateEntry.getRegionId()));
if (updateEntry.isInitial() == true) {
item.add(new Label("version", "initial"));
} else {
item.add(new Label("version", version.toString()));
}
final String description = updateEntry.getDescription();
item.add(new Label("description", StringUtils.isBlank(description) == true ? "" : description));
item.add(new Label("date", updateEntry.getDate()));
final String preCheckResult = updateEntry.getPreCheckResult();
item.add(new Label("preCheckResult", HtmlHelper.escapeHtml(preCheckResult, true)));
if (updateEntry.getPreCheckStatus() == UpdatePreCheckStatus.READY_FOR_UPDATE) {
final Button updateButton = new Button("button", new Model<String>("update")) {
@Override
public final void onSubmit()
{
parentPage.update(updateEntry);
}
};
item.add(new SingleButtonPanel("update", updateButton, "update"));
} else {
final String runningResult = updateEntry.getRunningResult();
item.add(new Label("update", HtmlHelper.escapeHtml(runningResult, true)));
}
}
}
/**
* @see org.projectforge.web.wicket.AbstractForm#onBeforeRender()
*/
@Override
public void onBeforeRender()
{
super.onBeforeRender();
actionButtons.render();
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_3 |
crossvul-java_data_good_510_1 | /*
* Copyright 2016 http://www.hswebframework.org
*
* 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 org.hswebframework.web.authorization.oauth2.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hswebframework.web.BusinessException;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2CodeAuthBeforeEvent;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.oauth2.client.OAuth2ServerConfigEntity;
import org.hswebframework.web.id.IDGenerator;
import org.hswebframework.web.oauth2.core.ErrorType;
import org.hswebframework.web.oauth2.core.OAuth2Constants;
import org.hswebframework.web.service.oauth2.client.OAuth2ServerConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* @author zhouhao
*/
@Controller
@RequestMapping("${hsweb.web.mappings.oauth2-client-callback:oauth2}")
@Api(tags = "OAuth2.0-客户端-请求服务", value = "OAuth2.0客户端请求服务")
public class OAuth2ClientController {
private OAuth2RequestService oAuth2RequestService;
private OAuth2ServerConfigService oAuth2ServerConfigService;
@Autowired
public void setoAuth2ServerConfigService(OAuth2ServerConfigService oAuth2ServerConfigService) {
this.oAuth2ServerConfigService = oAuth2ServerConfigService;
}
@Autowired
public void setoAuth2RequestService(OAuth2RequestService oAuth2RequestService) {
this.oAuth2RequestService = oAuth2RequestService;
}
private static final String STATE_SESSION_KEY = "OAUTH2_STATE";
@GetMapping("/state")
@ResponseBody
@ApiOperation("申请一个state")
public ResponseMessage<String> requestState(HttpSession session) {
String state = IDGenerator.RANDOM.generate();
session.setAttribute(STATE_SESSION_KEY, state);
return ResponseMessage.ok(state);
}
@GetMapping("/boot/{serverId}")
@ApiOperation("跳转至OAuth2.0服务授权页面")
public RedirectView boot(@PathVariable String serverId,
@RequestParam(defaultValue = "/") String redirect,
HttpServletRequest request,
HttpSession session) throws UnsupportedEncodingException {
OAuth2ServerConfigEntity entity = oAuth2ServerConfigService.selectByPk(serverId);
if (entity == null) {
return new RedirectView("/401.html");
}
String callback = WebUtil.getBasePath(request)
.concat("oauth2/callback/")
.concat(serverId).concat("/?redirect=")
.concat(URLEncoder.encode(redirect, "UTF-8"));
RedirectView view = new RedirectView(entity.getRealUrl(entity.getAuthUrl()));
view.addStaticAttribute(OAuth2Constants.response_type, "code");
view.addStaticAttribute(OAuth2Constants.state, requestState(session).getResult());
view.addStaticAttribute(OAuth2Constants.client_id, entity.getClientId());
view.addStaticAttribute(OAuth2Constants.redirect_uri, callback);
return view;
}
@GetMapping("/callback/{serverId}")
@ApiOperation(value = "OAuth2.0授权完成后回调", hidden = true)
public RedirectView callback(@RequestParam(defaultValue = "/") String redirect,
@PathVariable String serverId,
@RequestParam String code,
@RequestParam String state,
HttpServletRequest request,
HttpSession session) throws UnsupportedEncodingException {
try {
String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
if (!state.equals(cachedState)) {
throw new BusinessException(ErrorType.STATE_ERROR.name());
}
oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));
} finally {
session.removeAttribute(STATE_SESSION_KEY);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_510_1 |
crossvul-java_data_good_2031_4 | package org.jolokia.restrictor;
import java.io.IOException;
import java.io.InputStream;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jolokia.restrictor.policy.*;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Restrictor, which is based on a policy file
*
* @author roland
* @since Jul 28, 2009
*/
public class PolicyRestrictor implements Restrictor {
// Checks HTTP method restrictions
private HttpMethodChecker httpChecker;
// Checks for certain request types
private RequestTypeChecker requestTypeChecker;
// Check for hosts and subnets
private NetworkChecker networkChecker;
// Check for CORS access
private CorsChecker corsChecker;
// Check for MBean access
private MBeanAccessChecker mbeanAccessChecker;
/**
* Construct a policy restrictor from an input stream
*
* @param pInput stream from where to fetch the policy data
*/
public PolicyRestrictor(InputStream pInput) {
Exception exp = null;
if (pInput == null) {
throw new SecurityException("No policy file given");
}
try {
Document doc =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pInput);
requestTypeChecker = new RequestTypeChecker(doc);
httpChecker = new HttpMethodChecker(doc);
networkChecker = new NetworkChecker(doc);
mbeanAccessChecker = new MBeanAccessChecker(doc);
corsChecker = new CorsChecker(doc);
}
catch (SAXException e) { exp = e; }
catch (IOException e) { exp = e; }
catch (ParserConfigurationException e) { exp = e; }
catch (MalformedObjectNameException e) { exp = e; }
if (exp != null) {
throw new SecurityException("Cannot parse policy file: " + exp,exp);
}
}
/** {@inheritDoc} */
public boolean isHttpMethodAllowed(HttpMethod method) {
return httpChecker.check(method);
}
/** {@inheritDoc} */
public boolean isTypeAllowed(RequestType pType) {
return requestTypeChecker.check(pType);
}
/** {@inheritDoc} */
public boolean isRemoteAccessAllowed(String ... pHostOrAddress) {
return networkChecker.check(pHostOrAddress);
}
/** {@inheritDoc} */
public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) {
return corsChecker.check(pOrigin,pIsStrictCheck);
}
/** {@inheritDoc} */
public boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
return check(RequestType.READ,pName,pAttribute);
}
/** {@inheritDoc} */
public boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
return check(RequestType.WRITE,pName, pAttribute);
}
/** {@inheritDoc} */
public boolean isOperationAllowed(ObjectName pName, String pOperation) {
return check(RequestType.EXEC,pName, pOperation);
}
/** {@inheritDoc} */
private boolean check(RequestType pType, ObjectName pName, String pValue) {
return mbeanAccessChecker.check(new MBeanAccessChecker.Arg(isTypeAllowed(pType), pType, pName, pValue));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_4 |
crossvul-java_data_bad_5842_6 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.core;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.projectforge.access.AccessChecker;
import org.projectforge.user.PFUserContext;
import org.projectforge.user.UserRights;
import org.projectforge.user.UserXmlPreferencesCache;
import org.projectforge.web.FavoritesMenu;
import org.projectforge.web.LayoutSettingsPage;
import org.projectforge.web.LoginPage;
import org.projectforge.web.MenuEntry;
import org.projectforge.web.core.menuconfig.MenuConfig;
import org.projectforge.web.dialog.ModalDialog;
import org.projectforge.web.doc.DocumentationPage;
import org.projectforge.web.mobile.MenuMobilePage;
import org.projectforge.web.user.ChangePasswordPage;
import org.projectforge.web.user.MyAccountEditPage;
import org.projectforge.web.wicket.AbstractSecuredPage;
import org.projectforge.web.wicket.FeedbackPage;
import org.projectforge.web.wicket.MySession;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
/**
* Displays the favorite menu.
* @author Kai Reinhard (k.reinhard@micromata.de)
*/
public class NavTopPanel extends NavAbstractPanel
{
private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(NavTopPanel.class);
private static final long serialVersionUID = -7858806882044188339L;
private FavoritesMenu favoritesMenu;
private final AccessChecker accessChecker;
private final UserXmlPreferencesCache userXmlPreferencesCache;
private BookmarkDialog bookmarkDialog;
public NavTopPanel(final String id, final UserXmlPreferencesCache userXmlPreferencesCache, final AccessChecker accessChecker)
{
super(id);
this.userXmlPreferencesCache = userXmlPreferencesCache;
this.accessChecker = accessChecker;
}
public void init(final AbstractSecuredPage page)
{
getMenu();
this.favoritesMenu = FavoritesMenu.get();
final WebMarkupContainer goMobile = new WebMarkupContainer("goMobile");
add(goMobile);
if (page.getMySession().isMobileUserAgent() == true) {
goMobile.add(new BookmarkablePageLink<Void>("link", MenuMobilePage.class));
} else {
goMobile.setVisible(false);
}
final BookmarkablePageLink<Void> layoutSettingsMenuLink = new BookmarkablePageLink<Void>("layoutSettingsMenuLink",
LayoutSettingsPage.class);
if (UserRights.getAccessChecker().isRestrictedUser() == true) {
// Not visibible for restricted users:
layoutSettingsMenuLink.setVisible(false);
}
add(new MenuConfig("menuconfig", getMenu(), favoritesMenu));
@SuppressWarnings("serial")
final Form<String> searchForm = new Form<String>("searchForm") {
private String searchString;
/**
* @see org.apache.wicket.markup.html.form.Form#onSubmit()
*/
@Override
protected void onSubmit()
{
if (StringUtils.isNotBlank(searchString) == true) {
final SearchPage searchPage = new SearchPage(new PageParameters(), searchString);
setResponsePage(searchPage);
}
super.onSubmit();
}
};
add(searchForm);
final TextField<String> searchField = new TextField<String>("searchField", new PropertyModel<String>(searchForm, "searchString"));
WicketUtils.setPlaceHolderAttribute(searchField, getString("search.search"));
searchForm.add(searchField);
add(layoutSettingsMenuLink);
add(new BookmarkablePageLink<Void>("feedbackLink", FeedbackPage.class));
{
@SuppressWarnings("serial")
final AjaxLink<Void> showBookmarkLink = new AjaxLink<Void>("showBookmarkLink") {
/**
* @see org.apache.wicket.ajax.markup.html.AjaxLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
*/
@Override
public void onClick(final AjaxRequestTarget target)
{
bookmarkDialog.open(target);
// Redraw the content:
bookmarkDialog.redraw().addContent(target);
}
};
add(showBookmarkLink);
addBookmarkDialog();
}
{
add(new Label("user", PFUserContext.getUser().getFullname()));
if (accessChecker.isRestrictedUser() == true) {
// Show ChangePaswordPage as my account for restricted users.
final BookmarkablePageLink<Void> changePasswordLink = new BookmarkablePageLink<Void>("myAccountLink", ChangePasswordPage.class);
add(changePasswordLink);
} else {
final BookmarkablePageLink<Void> myAccountLink = new BookmarkablePageLink<Void>("myAccountLink", MyAccountEditPage.class);
add(myAccountLink);
}
final BookmarkablePageLink<Void> documentationLink = new BookmarkablePageLink<Void>("documentationLink", DocumentationPage.class);
add(documentationLink);
@SuppressWarnings("serial")
final Link<String> logoutLink = new Link<String>("logoutLink") {
@Override
public void onClick()
{
LoginPage.logout((MySession) getSession(), (WebRequest) getRequest(), (WebResponse) getResponse(), userXmlPreferencesCache);
setResponsePage(LoginPage.class);
};
};
add(logoutLink);
}
addCompleteMenu();
addFavoriteMenu();
}
@SuppressWarnings("serial")
private void addCompleteMenu()
{
final Label totalMenuSuffixLabel = new MenuSuffixLabel("totalMenuCounter", new Model<Integer>() {
@Override
public Integer getObject()
{
int counter = 0;
if (menu.getMenuEntries() == null) {
return counter;
}
for (final MenuEntry menuEntry : menu.getMenuEntries()) {
final IModel<Integer> newCounterModel = menuEntry.getNewCounterModel();
if (newCounterModel != null && newCounterModel.getObject() != null) {
counter += newCounterModel.getObject();
}
}
return counter;
};
});
add(totalMenuSuffixLabel);
final RepeatingView completeMenuCategoryRepeater = new RepeatingView("completeMenuCategoryRepeater");
add(completeMenuCategoryRepeater);
if (menu.getMenuEntries() != null) {
for (final MenuEntry menuEntry : menu.getMenuEntries()) {
if (menuEntry.getSubMenuEntries() == null) {
continue;
}
// Now we add a new menu area (title with sub menus):
final WebMarkupContainer categoryContainer = new WebMarkupContainer(completeMenuCategoryRepeater.newChildId());
completeMenuCategoryRepeater.add(categoryContainer);
categoryContainer.add(new Label("menuCategoryLabel", getString(menuEntry.getI18nKey())));
final Label areaSuffixLabel = getSuffixLabel(menuEntry);
categoryContainer.add(areaSuffixLabel);
// final WebMarkupContainer subMenuContainer = new WebMarkupContainer("subMenu");
// categoryContainer.add(subMenuContainer);
if (menuEntry.hasSubMenuEntries() == false) {
// subMenuContainer.setVisible(false);
continue;
}
final RepeatingView completeSubMenuRepeater = new RepeatingView("completeSubMenuRepeater");
categoryContainer.add(completeSubMenuRepeater);
for (final MenuEntry subMenuEntry : menuEntry.getSubMenuEntries()) {
if (subMenuEntry.getSubMenuEntries() != null) {
log.error("Oups: sub sub menus not supported: " + menuEntry.getId() + " has child menus which are ignored.");
}
// Now we add the next menu entry to the area:
final WebMarkupContainer subMenuItem = new WebMarkupContainer(completeSubMenuRepeater.newChildId());
completeSubMenuRepeater.add(subMenuItem);
final AbstractLink link = getMenuEntryLink(subMenuEntry, true);
if (link != null) {
subMenuItem.add(link);
} else {
subMenuItem.setVisible(false);
}
}
}
}
}
private void addFavoriteMenu()
{
// Favorite menu:
final RepeatingView menuRepeater = new RepeatingView("menuRepeater");
add(menuRepeater);
final Collection<MenuEntry> menuEntries = favoritesMenu.getMenuEntries();
if (menuEntries != null) {
for (final MenuEntry menuEntry : menuEntries) {
// Now we add a new menu area (title with sub menus):
final WebMarkupContainer menuItem = new WebMarkupContainer(menuRepeater.newChildId());
menuRepeater.add(menuItem);
final AbstractLink link = getMenuEntryLink(menuEntry, true);
if (link == null) {
menuItem.setVisible(false);
continue;
}
menuItem.add(link);
final WebMarkupContainer subMenuContainer = new WebMarkupContainer("subMenu");
menuItem.add(subMenuContainer);
final WebMarkupContainer caret = new WebMarkupContainer("caret");
link.add(caret);
if (menuEntry.hasSubMenuEntries() == false) {
subMenuContainer.setVisible(false);
caret.setVisible(false);
continue;
}
menuItem.add(AttributeModifier.append("class", "dropdown"));
link.add(AttributeModifier.append("class", "dropdown-toggle"));
link.add(AttributeModifier.append("data-toggle", "dropdown"));
final RepeatingView subMenuRepeater = new RepeatingView("subMenuRepeater");
subMenuContainer.add(subMenuRepeater);
for (final MenuEntry subMenuEntry : menuEntry.getSubMenuEntries()) {
// Now we add the next menu entry to the area:
if (subMenuEntry.hasSubMenuEntries() == false) {
final WebMarkupContainer subMenuItem = new WebMarkupContainer(subMenuRepeater.newChildId());
subMenuRepeater.add(subMenuItem);
// Subsubmenu entries aren't yet supported, show only the sub entries without children, otherwise only the children are
// displayed.
final AbstractLink subLink = getMenuEntryLink(subMenuEntry, true);
if (subLink == null) {
subMenuItem.setVisible(false);
continue;
}
subMenuItem.add(subLink);
continue;
}
// final WebMarkupContainer subsubMenuContainer = new WebMarkupContainer("subsubMenu");
// subMenuItem.add(subsubMenuContainer);
// if (subMenuEntry.hasSubMenuEntries() == false) {
// subsubMenuContainer.setVisible(false);
// continue;
// }
// final RepeatingView subsubMenuRepeater = new RepeatingView("subsubMenuRepeater");
// subsubMenuContainer.add(subsubMenuRepeater);
for (final MenuEntry subsubMenuEntry : subMenuEntry.getSubMenuEntries()) {
// Now we add the next menu entry to the sub menu:
final WebMarkupContainer subMenuItem = new WebMarkupContainer(subMenuRepeater.newChildId());
subMenuRepeater.add(subMenuItem);
// Subsubmenu entries aren't yet supported, show only the sub entries without children, otherwise only the children are
// displayed.
final AbstractLink subLink = getMenuEntryLink(subsubMenuEntry, true);
if (subLink == null) {
subMenuItem.setVisible(false);
continue;
}
subMenuItem.add(subLink);
// final WebMarkupContainer subsubMenuItem = new WebMarkupContainer(subsubMenuRepeater.newChildId());
// subsubMenuRepeater.add(subsubMenuItem);
// final AbstractLink subsubLink = getMenuEntryLink(subsubMenuEntry, subsubMenuItem);
// subsubMenuItem.add(subsubLink);
}
}
}
}
}
private void addBookmarkDialog()
{
final AbstractSecuredPage parentPage = (AbstractSecuredPage) getPage();
bookmarkDialog = new BookmarkDialog(parentPage.newModalDialogId());
bookmarkDialog.setOutputMarkupId(true);
parentPage.add(bookmarkDialog);
bookmarkDialog.init();
}
@SuppressWarnings("serial")
private class BookmarkDialog extends ModalDialog
{
/**
* @param id
*/
public BookmarkDialog(final String id)
{
super(id);
}
@Override
public void init()
{
setTitle(getString("bookmark.title"));
init(new Form<String>(getFormId()));
gridBuilder.newFormHeading(""); // Otherwise it's empty and an IllegalArgumentException is thrown.
}
private BookmarkDialog redraw()
{
clearContent();
final AbstractSecuredPage page = (AbstractSecuredPage) NavTopPanel.this.getPage();
{
final FieldsetPanel fs = gridBuilder.newFieldset(getString("bookmark.directPageLink")).setLabelSide(false);
final TextArea<String> textArea = new TextArea<String>(fs.getTextAreaId(), new Model<String>(page.getPageAsLink()));
fs.add(textArea);
textArea.add(AttributeModifier.replace("onClick", "$(this).select();"));
}
final PageParameters params = page.getBookmarkableInitialParameters();
if (params.isEmpty() == false) {
final FieldsetPanel fs = gridBuilder.newFieldset(getString(page.getTitleKey4BookmarkableInitialParameters())).setLabelSide(false);
final TextArea<String> textArea = new TextArea<String>(fs.getTextAreaId(), new Model<String>(page.getPageAsLink(params)));
fs.add(textArea);
textArea.add(AttributeModifier.replace("onClick", "$(this).select();"));
}
return this;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_6 |
crossvul-java_data_bad_3058_1 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public synchronized List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public synchronized void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return viewGroupMixIn.getViews(); }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
final Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
}
});
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
setJDKs(req.bindJSONToList(JDK.class, json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
checkPermission(ADMINISTER);
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
checkPermission(ADMINISTER);
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_3058_1 |
crossvul-java_data_bad_3058_2 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Failure;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.UnprotectedRootAction;
import hudson.model.User;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.util.HttpResponses;
import hudson.model.FreeStyleProject;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.OfflineCause;
import hudson.util.FormValidation;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.HttpResponse;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author kingfai
*
*/
public class JenkinsTest {
@Rule public JenkinsRule j = new JenkinsRule();
@Test
public void testIsDisplayNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName("displayName");
Jenkins jenkins = Jenkins.getInstance();
assertTrue(jenkins.isDisplayNameUnique("displayName1", curJobName));
assertTrue(jenkins.isDisplayNameUnique(jobName, curJobName));
}
@Test
public void testIsDisplayNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
assertFalse(jenkins.isDisplayNameUnique(displayName, curJobName));
}
@Test
public void testIsDisplayNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String displayName = "currentProjectDisplayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
// should be true as we don't test against the current job
assertTrue(jenkins.isDisplayNameUnique(displayName, curJobName));
}
@Test
public void testIsNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
assertTrue(jenkins.isNameUnique("jobName1", curJobName));
}
@Test
public void testIsNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
assertFalse(jenkins.isNameUnique(jobName, curJobName));
}
@Test
public void testIsNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
// true because we don't test against the current job
assertTrue(jenkins.isNameUnique(curJobName, curJobName));
}
@Test
public void testDoCheckDisplayNameUnique() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName("displayName");
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName("1displayName", curJobName);
assertEquals(FormValidation.ok(), v);
}
@Test
public void testDoCheckDisplayNameSameAsDisplayName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName(displayName, curJobName);
assertEquals(FormValidation.Kind.WARNING, v.kind);
}
@Test
public void testDoCheckDisplayNameSameAsJobName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName(jobName, curJobName);
assertEquals(FormValidation.Kind.WARNING, v.kind);
}
@Test
public void testDoCheckViewName_GoodName() throws Exception {
String[] viewNames = new String[] {
"", "Jenkins"
};
Jenkins jenkins = Jenkins.getInstance();
for (String viewName : viewNames) {
FormValidation v = jenkins.doCheckViewName(viewName);
assertEquals(FormValidation.Kind.OK, v.kind);
}
}
@Test
public void testDoCheckViewName_NotGoodName() throws Exception {
String[] viewNames = new String[] {
"Jenkins?", "Jenkins*", "Jenkin/s", "Jenkin\\s", "jenkins%",
"Jenkins!", "Jenkins[]", "Jenkin<>s", "^Jenkins", ".."
};
Jenkins jenkins = Jenkins.getInstance();
for (String viewName : viewNames) {
FormValidation v = jenkins.doCheckViewName(viewName);
assertEquals(FormValidation.Kind.ERROR, v.kind);
}
}
@Test @Issue("JENKINS-12251")
public void testItemFullNameExpansion() throws Exception {
HtmlForm f = j.createWebClient().goTo("configure").getFormByName("config");
f.getInputByName("_.rawBuildsDir").setValueAttribute("${JENKINS_HOME}/test12251_builds/${ITEM_FULL_NAME}");
f.getInputByName("_.rawWorkspaceDir").setValueAttribute("${JENKINS_HOME}/test12251_ws/${ITEM_FULL_NAME}");
j.submit(f);
// build a dummy project
MavenModuleSet m = j.createMavenProject();
m.setScm(new ExtractResourceSCM(getClass().getResource("/simple-projects.zip")));
MavenModuleSetBuild b = m.scheduleBuild2(0).get();
// make sure these changes are effective
assertTrue(b.getWorkspace().getRemote().contains("test12251_ws"));
assertTrue(b.getRootDir().toString().contains("test12251_builds"));
}
/**
* Makes sure access to "/foobar" for UnprotectedRootAction gets through.
*/
@Test @Issue("JENKINS-14113")
public void testUnprotectedRootAction() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
WebClient wc = j.createWebClient();
wc.goTo("foobar");
wc.goTo("foobar/");
wc.goTo("foobar/zot");
// and make sure this fails
wc.assertFails("foobar-zot/", HttpURLConnection.HTTP_INTERNAL_ERROR);
assertEquals(3,j.jenkins.getExtensionList(RootAction.class).get(RootActionImpl.class).count);
}
@Test
public void testDoScript() throws Exception {
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
@Override public boolean hasPermission(String sid, Permission p) {
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
}
};
gmas.add(Jenkins.ADMINISTER, "alice");
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
gmas.add(Jenkins.READ, "bob");
gmas.add(Jenkins.ADMINISTER, "charlie");
j.jenkins.setAuthorizationStrategy(gmas);
WebClient wc = j.createWebClient();
wc.login("alice");
wc.goTo("script");
wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD);
assertNull(System.getProperty("hack"));
WebRequest req = new WebRequest(new URL(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST);
wc.getPage(wc.addCrumb(req));
assertEquals("me", System.getProperty("hack"));
wc.assertFails("scriptText?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD);
req = new WebRequest(new URL(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST);
wc.getPage(wc.addCrumb(req));
assertEquals("you", System.getProperty("huck"));
wc.login("bob");
wc.assertFails("script", HttpURLConnection.HTTP_FORBIDDEN);
wc.login("charlie");
wc.assertFails("script", HttpURLConnection.HTTP_FORBIDDEN);
}
@Test
public void testDoEval() throws Exception {
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
@Override public boolean hasPermission(String sid, Permission p) {
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
}
};
gmas.add(Jenkins.ADMINISTER, "alice");
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
gmas.add(Jenkins.READ, "bob");
gmas.add(Jenkins.ADMINISTER, "charlie");
j.jenkins.setAuthorizationStrategy(gmas);
WebClient wc = j.createWebClient();
wc.login("alice");
wc.assertFails("eval", HttpURLConnection.HTTP_BAD_METHOD);
assertEquals("3", eval(wc));
wc.login("bob");
try {
eval(wc);
fail("bob has only READ");
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
wc.login("charlie");
try {
eval(wc);
fail("charlie has ADMINISTER but not RUN_SCRIPTS");
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
}
private String eval(WebClient wc) throws Exception {
WebRequest req = new WebRequest(wc.createCrumbedUrl("eval"), HttpMethod.POST);
req.setEncodingType(null);
req.setRequestBody("<j:jelly xmlns:j='jelly:core'>${1+2}</j:jelly>");
return wc.getPage(req).getWebResponse().getContentAsString();
}
@TestExtension("testUnprotectedRootAction")
public static class RootActionImpl implements UnprotectedRootAction {
private int count;
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "foobar";
}
public HttpResponse doDynamic() {
assertTrue(Jenkins.getInstance().getAuthentication().getName().equals("anonymous"));
count++;
return HttpResponses.html("OK");
}
}
@TestExtension("testUnprotectedRootAction")
public static class ProtectedRootActionImpl implements RootAction {
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "foobar-zot";
}
public HttpResponse doDynamic() {
throw new AssertionError();
}
}
@Test @Issue("JENKINS-20866")
public void testErrorPageShouldBeAnonymousAccessible() throws Exception {
HudsonPrivateSecurityRealm s = new HudsonPrivateSecurityRealm(false, false, null);
User alice = s.createAccount("alice", "alice");
j.jenkins.setSecurityRealm(s);
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
// no anonymous read access
assertTrue(!Jenkins.getInstance().getACL().hasPermission(Jenkins.ANONYMOUS,Jenkins.READ));
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("error/reportError");
assertEquals(p.asText(), 400, p.getWebResponse().getStatusCode()); // not 403 forbidden
assertTrue(p.getWebResponse().getContentAsString().contains("My car is black"));
}
@TestExtension("testErrorPageShouldBeAnonymousAccessible")
public static class ReportError implements UnprotectedRootAction {
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "error";
}
public HttpResponse doReportError() {
return new Failure("My car is black");
}
}
@Test @Issue("JENKINS-23551")
public void testComputerListenerNotifiedOnRestart() {
// Simulate restart calling listeners
for (RestartListener listener : RestartListener.all())
listener.onRestart();
ArgumentCaptor<OfflineCause> captor = ArgumentCaptor.forClass(OfflineCause.class);
Mockito.verify(listenerMock).onOffline(Mockito.eq(j.jenkins.toComputer()), captor.capture());
assertTrue(captor.getValue().toString().contains("restart"));
}
@TestExtension(value = "testComputerListenerNotifiedOnRestart")
public static final ComputerListener listenerMock = Mockito.mock(ComputerListener.class);
@Test
public void runScriptOnOfflineComputer() throws Exception {
DumbSlave slave = j.createSlave(true);
j.disconnectSlave(slave);
URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)");
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
WebRequest req = new WebRequest(url, HttpMethod.POST);
Page page = wc.getPage(wc.addCrumb(req));
WebResponse rsp = page.getWebResponse();
assertThat(rsp.getContentAsString(), containsString("Node is offline"));
assertThat(rsp.getStatusCode(), equalTo(404));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_3058_2 |
crossvul-java_data_bad_5842_8 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.dialog;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.projectforge.web.core.NavTopPanel;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.MyComponentsRepeater;
import de.micromata.wicket.ajax.AjaxCallback;
import de.micromata.wicket.ajax.AjaxFormSubmitCallback;
/**
* Base component for the ProjectForge modal dialogs.<br/>
* This dialog is modal.<br/>
*
* @author Johannes Unterstein (j.unterstein@micromata.de)
* @author Kai Reinhard (k.reinhard@micromata.de)
*
*/
public abstract class ModalDialog extends Panel
{
private static final long serialVersionUID = 4235521713603821639L;
protected GridBuilder gridBuilder;
protected final WebMarkupContainer mainContainer, mainSubContainer, gridContentContainer, buttonBarContainer;
private boolean escapeKeyEnabled = true;
private String closeButtonLabel;
private SingleButtonPanel closeButtonPanel;
private boolean showCancelButton;
private boolean bigWindow;
private boolean draggable = true;
private Boolean resizable;
private boolean lazyBinding;
private WebMarkupContainer titleContainer;
private Label titleLabel;
protected Form< ? > form;
protected FeedbackPanel formFeedback;
/**
* If true, a GridBuilder is automatically available.
*/
protected boolean autoGenerateGridBuilder = true;
/**
* List to create action buttons in the desired order before creating the RepeatingView.
*/
protected MyComponentsRepeater<Component> actionButtons;
/**
* @param id
*/
public ModalDialog(final String id)
{
super(id);
actionButtons = new MyComponentsRepeater<Component>("actionButtons");
mainContainer = new WebMarkupContainer("mainContainer");
add(mainContainer.setOutputMarkupId(true));
mainContainer.add(mainSubContainer = new WebMarkupContainer("mainSubContainer"));
gridContentContainer = new WebMarkupContainer("gridContent");
gridContentContainer.setOutputMarkupId(true);
buttonBarContainer = new WebMarkupContainer("buttonBar");
buttonBarContainer.setOutputMarkupId(true);
}
/**
* @see org.apache.wicket.Component#onInitialize()
*/
@Override
protected void onInitialize()
{
super.onInitialize();
if (bigWindow == true) {
mainContainer.add(AttributeModifier.append("class", "big-modal"));
}
}
/**
* Sets also draggable to false. Appends css class big-modal.
*/
public ModalDialog setBigWindow()
{
bigWindow = true;
draggable = false;
return this;
}
/**
* Only the div panel of the modal dialog is rendered without buttons and content. Default is false.
* @return this for chaining.
*/
public ModalDialog setLazyBinding()
{
this.lazyBinding = true;
mainSubContainer.setVisible(false);
return this;
}
public void bind(final AjaxRequestTarget target)
{
actionButtons.render();
mainSubContainer.setVisible(true);
target.appendJavaScript(getJavaScriptAction());
}
/**
* @return true if no lazy binding was used or bind() was already called.
*/
public boolean isBound()
{
return mainSubContainer.isVisible();
}
/**
* @param draggable the draggable to set (default is true).
* @return this for chaining.
*/
public ModalDialog setDraggable(final boolean draggable)
{
this.draggable = draggable;
return this;
}
/**
* @param resizable the resizable to set (default is true for bigWindows, otherwise false).
* @return this for chaining.
*/
public ModalDialog setResizable(final boolean resizable)
{
this.resizable = resizable;
return this;
}
/**
* Display the cancel button.
* @return this for chaining.
*/
public ModalDialog setShowCancelButton()
{
this.showCancelButton = true;
return this;
}
/**
* @param escapeKeyEnabled the keyboard to set (default is true).
* @return this for chaining.
*/
public ModalDialog setEscapeKeyEnabled(final boolean escapeKeyEnabled)
{
this.escapeKeyEnabled = escapeKeyEnabled;
return this;
}
/**
* Close is used as default:
* @param closeButtonLabel the closeButtonLabel to set
* @return this for chaining.
*/
public ModalDialog setCloseButtonLabel(final String closeButtonLabel)
{
this.closeButtonLabel = closeButtonLabel;
return this;
}
/**
* Should be called directly after {@link #init()}.
* @param tooltipTitle
* @param tooltipContent
* @see WicketUtils#addTooltip(Component, IModel, IModel)
*/
public ModalDialog setCloseButtonTooltip(final IModel<String> tooltipTitle, final IModel<String> tooltipContent)
{
WicketUtils.addTooltip(this.closeButtonPanel.getButton(), tooltipTitle, tooltipContent);
return this;
}
@SuppressWarnings("serial")
public ModalDialog wantsNotificationOnClose()
{
mainContainer.add(new AjaxEventBehavior("hidden") {
@Override
protected void onEvent(final AjaxRequestTarget target)
{
handleCloseEvent(target);
}
});
return this;
}
public ModalDialog addAjaxEventBehavior(final AjaxEventBehavior behavior)
{
mainContainer.add(behavior);
return this;
}
public String getMainContainerMarkupId()
{
return mainContainer.getMarkupId(true);
}
@Override
public void renderHead(final IHeaderResponse response)
{
super.renderHead(response);
if (lazyBinding == false) {
final String script = getJavaScriptAction();
response.render(OnDomReadyHeaderItem.forScript(script));
}
}
private String getJavaScriptAction()
{
final StringBuffer script = new StringBuffer();
script.append("$('#").append(getMainContainerMarkupId()).append("').modal({keyboard: ").append(escapeKeyEnabled)
.append(", show: false });");
final boolean isResizable = (resizable == null && bigWindow == true) || Boolean.TRUE.equals(resizable) == true;
if (draggable == true || isResizable == true) {
script.append(" $('#").append(getMainContainerMarkupId()).append("')");
}
if (draggable == true) {
script.append(".draggable()");
}
if (isResizable) {
script.append(".resizable({ alsoResize: '#")
.append(getMainContainerMarkupId())
// max-height of .modal-body is 600px, need to enlarge this setting for resizing.
.append(
", .modal-body', resize: function( event, ui ) {$('.modal-body').css('max-height', '4000px');}, minWidth: 300, minHeight: 200 })");
}
return script.toString();
}
public ModalDialog open(final AjaxRequestTarget target)
{
target.appendJavaScript("$('#" + getMainContainerMarkupId() + "').modal('show');");
return this;
}
public void close(final AjaxRequestTarget target)
{
target.appendJavaScript("$('#" + getMainContainerMarkupId() + "').modal('hide');");
}
/**
* Add the content to the AjaxRequestTarget if the content is changed.
* @param target
* @return this for chaining.
*/
public ModalDialog addContent(final AjaxRequestTarget target)
{
target.add(gridContentContainer);
return this;
}
/**
* Add the button bar to the AjaxRequestTarget if the buttons or their visibility are changed.
* @param target
* @return this for chaining.
*/
public ModalDialog addButtonBar(final AjaxRequestTarget target)
{
target.add(buttonBarContainer);
return this;
}
/**
* @param target
* @return this for chaining.
*/
public ModalDialog addTitleLabel(final AjaxRequestTarget target)
{
target.add(titleLabel);
return this;
}
public abstract void init();
/**
* @param title
* @return this for chaining.
*/
public ModalDialog setTitle(final String title)
{
return setTitle(Model.of(title));
}
/**
* @param title
* @return this for chaining.
*/
public ModalDialog setTitle(final IModel<String> title)
{
titleContainer = new WebMarkupContainer("titleContainer");
mainSubContainer.add(titleContainer.setOutputMarkupId(true));
titleContainer.add(titleLabel = new Label("titleText", title));
titleLabel.setOutputMarkupId(true);
return this;
}
/**
* The gridContentContainer is cleared (all child elements are removed). This is useful for Ajax dialogs with dynamic content (see
* {@link NavTopPanel} for an example).
* @return
*/
public ModalDialog clearContent()
{
gridContentContainer.removeAll();
if (autoGenerateGridBuilder == true) {
gridBuilder = new GridBuilder(gridContentContainer, "flowform");
}
initFeedback(gridContentContainer);
return this;
}
@SuppressWarnings("serial")
protected void init(final Form< ? > form)
{
this.form = form;
mainSubContainer.add(form);
form.add(gridContentContainer);
form.add(buttonBarContainer);
if (showCancelButton == true) {
final SingleButtonPanel cancelButton = appendNewAjaxActionButton(new AjaxCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
onCancelButtonSubmit(target);
close(target);
}
}, getString("cancel"), SingleButtonPanel.CANCEL);
cancelButton.getButton().setDefaultFormProcessing(false);
}
closeButtonPanel = appendNewAjaxActionButton(new AjaxFormSubmitCallback() {
@Override
public void callback(final AjaxRequestTarget target)
{
if (onCloseButtonSubmit(target)) {
close(target);
}
}
@Override
public void onError(final AjaxRequestTarget target, final Form< ? > form)
{
ModalDialog.this.onError(target, form);
}
}, closeButtonLabel != null ? closeButtonLabel : getString("close"), SingleButtonPanel.NORMAL);
buttonBarContainer.add(actionButtons.getRepeatingView());
form.setDefaultButton(closeButtonPanel.getButton());
if (autoGenerateGridBuilder == true) {
gridBuilder = new GridBuilder(gridContentContainer, "flowform");
}
initFeedback(gridContentContainer);
}
private void initFeedback(final WebMarkupContainer container)
{
if (formFeedback == null) {
formFeedback = new FeedbackPanel("formFeedback", new ComponentFeedbackMessageFilter(form));
formFeedback.setOutputMarkupId(true);
formFeedback.setOutputMarkupPlaceholderTag(true);
}
container.add(formFeedback);
}
protected void ajaxError(final String error, final AjaxRequestTarget target)
{
form.error(error);
target.add(formFeedback);
}
/**
* Called if {@link #wantsNotificationOnClose()} was chosen and the dialog is closed (by pressing esc, clicking outside or clicking the
* upper right cross).
* @param target
*/
protected void handleCloseEvent(final AjaxRequestTarget target)
{
}
/**
* Called if user hit the cancel button.
* @param target
*/
protected void onCancelButtonSubmit(final AjaxRequestTarget target)
{
}
/**
* Called if user hit the close button.
*
* @param target
*
* @return true if the dialog can be close, false if errors occured.
*/
protected boolean onCloseButtonSubmit(final AjaxRequestTarget target)
{
return true;
}
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
}
/**
* @see org.apache.wicket.Component#onBeforeRender()
*/
@Override
protected void onBeforeRender()
{
super.onBeforeRender();
if (lazyBinding == false) {
actionButtons.render();
}
}
public String getFormId()
{
return "form";
}
public SingleButtonPanel appendNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
final SingleButtonPanel result = addNewAjaxActionButton(ajaxCallback, label, classnames);
this.actionButtons.add(result);
return result;
}
public SingleButtonPanel prependNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
return insertNewAjaxActionButton(ajaxCallback, 0, label, classnames);
}
/**
* @param ajaxCallback
* @param position 0 is the first position.
* @param label
* @param classnames
* @return
*/
public SingleButtonPanel insertNewAjaxActionButton(final AjaxCallback ajaxCallback, final int position, final String label,
final String... classnames)
{
final SingleButtonPanel result = addNewAjaxActionButton(ajaxCallback, label, classnames);
this.actionButtons.add(position, result);
return result;
}
private SingleButtonPanel addNewAjaxActionButton(final AjaxCallback ajaxCallback, final String label, final String... classnames)
{
final AjaxButton button = new AjaxButton("button", form) {
private static final long serialVersionUID = -5306532706450731336L;
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)
{
ajaxCallback.callback(target);
}
@Override
protected void onError(final AjaxRequestTarget target, final Form< ? > form)
{
if (ajaxCallback instanceof AjaxFormSubmitCallback) {
((AjaxFormSubmitCallback) ajaxCallback).onError(target, form);
}
}
};
final SingleButtonPanel buttonPanel = new SingleButtonPanel(this.actionButtons.newChildId(), button, label, classnames);
buttonPanel.add(button);
return buttonPanel;
}
/**
* @return the mainContainer
*/
public WebMarkupContainer getMainContainer()
{
return mainContainer;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_8 |
crossvul-java_data_good_5842_11 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.mobile;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.projectforge.core.AbstractBaseDO;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.mobileflowlayout.MobileGridBuilder;
public abstract class AbstractMobileEditForm<O extends AbstractBaseDO< ? >, P extends AbstractMobileEditPage< ? , ? , ? >> extends
AbstractMobileForm<O, P>
{
private static final long serialVersionUID = 1836099012618517190L;
protected O data;
protected MobileGridBuilder gridBuilder;
/**
* Cross site request forgery token.
*/
private final CsrfTokenHandler csrfTokenHandler;
public AbstractMobileEditForm(final P parentPage, final O data)
{
super(parentPage);
this.data = data;
csrfTokenHandler = new CsrfTokenHandler(this);
}
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
public O getData()
{
return this.data;
}
public void setData(final O data)
{
this.data = data;
}
public boolean isNew()
{
return this.data == null || this.data.getId() == null;
}
@SuppressWarnings("serial")
protected void init()
{
add(new FeedbackPanel("feedback").setOutputMarkupId(true));
final SubmitLink submitButton = new SubmitLink("submitButton") {
@Override
public final void onSubmit()
{
parentPage.save();
}
};
final RepeatingView flowform = new RepeatingView("flowform");
add(flowform);
gridBuilder = newGridBuilder(flowform);
add(submitButton);
if (isNew() == true) {
submitButton.add(new Label("label", getString("create")));
} else {
submitButton.add(new Label("label", getString("update")));
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_11 |
crossvul-java_data_good_510_0 | /*
* Copyright 2016 http://www.hswebframework.org
*
* 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 org.hswebframework.web.oauth2.core;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public enum ErrorType {
ILLEGAL_CODE(1001), //错误的授权码
ILLEGAL_ACCESS_TOKEN(1002), //错误的access_token
ILLEGAL_CLIENT_ID(1003),//客户端信息错误
ILLEGAL_CLIENT_SECRET(1004),//客户端密钥错误
ILLEGAL_GRANT_TYPE(1005), //错误的授权方式
ILLEGAL_RESPONSE_TYPE(1006),//response_type 错误
ILLEGAL_AUTHORIZATION(1007),//Authorization 错误
ILLEGAL_REFRESH_TOKEN(1008),//refresh_token 错误
ILLEGAL_REDIRECT_URI(1009), //redirect_url 错误
ILLEGAL_SCOPE(1010), //scope 错误
ILLEGAL_USERNAME(1011), //username 错误
ILLEGAL_PASSWORD(1012), //password 错误
SCOPE_OUT_OF_RANGE(2010), //scope超出范围
UNAUTHORIZED_CLIENT(4010), //无权限
EXPIRED_TOKEN(4011), //TOKEN过期
INVALID_TOKEN(4012), //TOKEN已失效
UNSUPPORTED_GRANT_TYPE(4013), //不支持的认证类型
UNSUPPORTED_RESPONSE_TYPE(4014), //不支持的响应类型
EXPIRED_CODE(4015), //AUTHORIZATION_CODE过期
EXPIRED_REFRESH_TOKEN(4020), //REFRESH_TOKEN过期
CLIENT_DISABLED(4016),//客户端已被禁用
CLIENT_NOT_EXIST(4040),//客户端不存在
USER_NOT_EXIST(4041),//客户端不存在
STATE_ERROR(4042), //stat错误
ACCESS_DENIED(503), //访问被拒绝
OTHER(5001), //其他错误 ;
PARSE_RESPONSE_ERROR(5002),//解析返回结果错误
SERVICE_ERROR(5003); //服务器返回错误信息
private final String message;
private final int code;
static final Map<Integer, ErrorType> codeMapping = Arrays.stream(ErrorType.values())
.collect(Collectors.toMap(ErrorType::code, type -> type));
ErrorType(int code) {
this.code = code;
message = this.name().toLowerCase();
}
ErrorType(int code, String message) {
this.message = message;
this.code = code;
}
public String message() {
if (message == null) {
return this.name();
}
return message;
}
public int code() {
return code;
}
public <T> T throwThis(Function<ErrorType, ? extends RuntimeException> errorTypeFunction) {
throw errorTypeFunction.apply(this);
}
public <T> T throwThis(BiFunction<ErrorType, String, ? extends RuntimeException> errorTypeFunction, String message) {
throw errorTypeFunction.apply(this, message);
}
public static Optional<ErrorType> fromCode(int code) {
return Optional.ofNullable(codeMapping.get(code));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_510_0 |
crossvul-java_data_good_2031_8 | package org.jolokia.http;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.io.*;
import java.net.SocketException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jolokia.backend.TestDetector;
import org.jolokia.config.ConfigKey;
import org.jolokia.discovery.JolokiaDiscovery;
import org.jolokia.restrictor.AllowAllRestrictor;
import org.jolokia.test.util.HttpTestUtil;
import org.jolokia.util.LogHandler;
import org.jolokia.util.NetworkUtil;
import org.json.simple.JSONObject;
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 30.08.11
*/
public class AgentServletTest {
private ServletContext context;
private ServletConfig config;
private HttpServletRequest request;
private HttpServletResponse response;
private AgentServlet servlet;
@Test
public void simpleInit() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(null, null,"No access restrictor found", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithAcessRestriction() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "classpath:/access-sample1.xml"},
null,
"Using access restrictor.*access-sample1.xml", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithInvalidPolicyFile() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "file:///blablub.xml"},
null,
"Error.*blablub.xml.*Denying", FileNotFoundException.class);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void configWithOverWrite() throws ServletException {
servlet = new AgentServlet();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
initConfigMocks(new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/jmx4perl",ConfigKey.MAX_DEPTH.getKeyValue(),"10"},
new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/j0l0k14",ConfigKey.MAX_OBJECTS.getKeyValue(),"20",
ConfigKey.CALLBACK.getKeyValue(),"callback is a request option, must be empty here"},
null,null);
replay(config, context,request,response);
servlet.init(config);
servlet.destroy();
org.jolokia.config.Configuration cfg = servlet.initConfig(config);
assertEquals(cfg.get(ConfigKey.AGENT_CONTEXT), "/j0l0k14");
assertEquals(cfg.get(ConfigKey.MAX_DEPTH), "10");
assertEquals(cfg.get(ConfigKey.MAX_OBJECTS), "20");
assertNull(cfg.get(ConfigKey.CALLBACK));
assertNull(cfg.get(ConfigKey.DETECTOR_OPTIONS));
}
@Test
public void initWithcustomAccessRestrictor() throws ServletException {
prepareStandardInitialisation();
servlet.destroy();
}
@Test
public void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andStubReturn(context);
expect(config.getServletName()).andStubReturn("jolokia");
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
}
@Test
public void initWithAgentDiscoveryAndGivenUrl() throws ServletException, IOException, InterruptedException {
checkMulticastAvailable();
String url = "http://localhost:8080/jolokia";
prepareStandardInitialisation(ConfigKey.DISCOVERY_AGENT_URL.getKeyValue(), url);
// Wait listening thread to warm up
Thread.sleep(1000);
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgentsWithTimeout(500);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
return;
}
}
fail("No agent found");
} finally {
servlet.destroy();
}
}
@Test
public void initWithAgentDiscoveryAndUrlLookup() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
// At least one doesnt have an URL (remove this part if a way could be found for getting
// to the URL
for (JSONObject json : in) {
if (json.get("url") == null) {
return;
}
}
fail("Every message has an URL");
} finally {
servlet.destroy();
}
}
private void checkMulticastAvailable() throws SocketException {
if (!NetworkUtil.isMulticastSupported()) {
throw new SkipException("No multicast interface found, skipping test ");
}
}
@Test
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
String url = "http://10.9.11.1:9876/jolokia";
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn(buf.toString());
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
}
public static class CustomLogHandler implements LogHandler {
private static int infoCount = 0;
public CustomLogHandler() {
infoCount = 0;
}
public void debug(String message) {
}
public void info(String message) {
infoCount++;
}
public void error(String message, Throwable t) {
}
}
@Test
public void simpleGet() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
Vector params = new Vector();
params.add("debug");
expect(request.getParameterNames()).andReturn(params.elements());
expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request,response);
servlet.doGet(request,response);
servlet.destroy();
}
@Test
public void simplePost() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter responseWriter = initRequestResponseMocks();
expect(request.getCharacterEncoding()).andReturn("utf-8");
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
preparePostRequest(HttpTestUtil.HEAP_MEMORY_POST_REQUEST);
replay(request, response);
servlet.doPost(request, response);
assertTrue(responseWriter.toString().contains("used"));
servlet.destroy();
}
@Test
public void unknownMethodWhenSettingContentType() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
expectLastCall().andThrow(new NoSuchMethodError());
response.setContentType("text/plain; charset=utf-8");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void corsPreflightCheck() throws ServletException, IOException {
checkCorsOriginPreflight("http://bla.com", "http://bla.com");
}
@Test
public void corsPreflightCheckWithNullOrigin() throws ServletException, IOException {
checkCorsOriginPreflight("null", "*");
}
private void checkCorsOriginPreflight(String in, String out) throws ServletException, IOException {
prepareStandardInitialisation();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getHeader("Access-Control-Request-Headers")).andReturn(null);
response.setHeader(eq("Access-Control-Allow-Max-Age"), (String) anyObject());
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials", "true");
replay(request, response);
servlet.doOptions(request, response);
servlet.destroy();
}
@Test
public void corsHeaderGetCheck() throws ServletException, IOException {
checkCorsGetOrigin("http://bla.com","http://bla.com");
}
@Test
public void corsHeaderGetCheckWithNullOrigin() throws ServletException, IOException {
checkCorsGetOrigin("null","*");
}
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
}
private void setNoCacheHeaders(HttpServletResponse pResp) {
pResp.setHeader("Cache-Control", "no-cache");
pResp.setHeader("Pragma","no-cache");
pResp.setDateHeader(eq("Date"),anyLong());
pResp.setDateHeader(eq("Expires"),anyLong());
}
@Test
public void withCallback() throws IOException, ServletException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
"myCallback",
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
response.setContentType("text/javascript");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().matches("^myCallback\\(.*\\);$"));
servlet.destroy();
}
@Test
public void withException() throws ServletException, IOException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(null, null,"Error 500", IllegalStateException.class);
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andThrow(new IllegalStateException());
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
String resp = sw.toString();
assertTrue(resp.contains("error_type"));
assertTrue(resp.contains("IllegalStateException"));
assertTrue(resp.matches(".*status.*500.*"));
servlet.destroy();
verify(config, context, request, response);
}
@Test
public void debug() throws IOException, ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null);
context.log(find("URI:"));
context.log(find("Path-Info:"));
context.log(find("Request:"));
context.log(find("time:"));
context.log(find("Response:"));
context.log(find("TestDetector"),isA(RuntimeException.class));
expectLastCall().asStub();
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@BeforeMethod
void resetTestDetector() {
TestDetector.reset();
}
//@AfterMethod
public void verifyMocks() {
verify(config, context, request, response);
}
// ============================================================================================
private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) {
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];
params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();
params[params.length - 1] = "true";
HttpTestUtil.prepareServletConfigMock(config,params);
HttpTestUtil.prepareServletContextMock(context, pContextParams);
expect(config.getServletContext()).andStubReturn(context);
expect(config.getServletName()).andStubReturn("jolokia");
if (pExceptionClass != null) {
context.log(find(pLogRegexp),isA(pExceptionClass));
} else {
if (pLogRegexp != null) {
context.log(find(pLogRegexp));
} else {
context.log((String) anyObject());
}
}
context.log((String) anyObject());
expectLastCall().asStub();
context.log(find("TestDetector"),isA(RuntimeException.class));
}
private StringWriter initRequestResponseMocks() throws IOException {
return initRequestResponseMocks(
getStandardRequestSetup(),
getStandardResponseSetup());
}
private StringWriter initRequestResponseMocks(Runnable requestSetup,Runnable responseSetup) throws IOException {
return initRequestResponseMocks(null,requestSetup,responseSetup);
}
private StringWriter initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException {
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
setNoCacheHeaders(response);
expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback);
requestSetup.run();
responseSetup.run();
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
expect(response.getWriter()).andReturn(writer);
return sw;
}
private void preparePostRequest(String pReq) throws IOException {
ServletInputStream is = HttpTestUtil.createServletInputStream(pReq);
expect(request.getInputStream()).andReturn(is);
}
private void prepareStandardInitialisation(String ... params) throws ServletException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(params.length > 0 ? params : null, null,"custom access", null);
replay(config, context);
servlet.init(config);
}
private Runnable getStandardResponseSetup() {
return new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
};
}
private Runnable getStandardRequestSetup() {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
};
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_8 |
crossvul-java_data_bad_2031_9 | package org.jolokia.http;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.management.*;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import org.jolokia.config.Configuration;
import org.jolokia.backend.BackendManager;
import org.jolokia.request.JmxReadRequest;
import org.jolokia.request.JmxRequest;
import org.jolokia.test.util.HttpTestUtil;
import org.jolokia.util.LogHandler;
import org.jolokia.util.RequestType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.testng.annotations.*;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 31.08.11
*/
public class HttpRequestHandlerTest {
private BackendManager backend;
private HttpRequestHandler handler;
@BeforeMethod
public void setup() {
backend = createMock(BackendManager.class);
expect(backend.isDebug()).andReturn(true).anyTimes();
handler = new HttpRequestHandler(new Configuration(),backend, createDummyLogHandler());
}
@AfterMethod
public void tearDown() {
verify(backend);
}
@Test
public void accessAllowed() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
replay(backend);
handler.checkClientIPAccess("localhost","127.0.0.1");
}
@Test(expectedExceptions = { SecurityException.class })
public void accessDenied() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false);
replay(backend);
handler.checkClientIPAccess("localhost","127.0.0.1");
}
@Test
public void get() throws InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp);
replay(backend);
JSONObject response = (JSONObject) handler.handleGetRequest("/jolokia", HttpTestUtil.HEAP_MEMORY_GET_REQUEST, null);
assertTrue(response == resp);
}
@Test
public void getWithDoubleSlashes() throws MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(eqReadRequest("read", "bla:type=s/lash/", "attribute"))).andReturn(resp);
replay(backend);
JSONObject response = (JSONObject) handler.handleGetRequest("/read/bla%3Atype%3Ds!/lash!//attribute",
"/read/bla:type=s!/lash!/Ok",null);
assertTrue(response == resp);
}
private JmxRequest eqReadRequest(String pType, final String pMBean, final String pAttribute) {
EasyMock.reportMatcher(new IArgumentMatcher() {
public boolean matches(Object argument) {
try {
JmxReadRequest req = (JmxReadRequest) argument;
return req.getType() == RequestType.READ &&
new ObjectName(pMBean).equals(req.getObjectName()) &&
pAttribute.equals(req.getAttributeName());
} catch (MalformedObjectNameException e) {
return false;
}
}
public void appendTo(StringBuffer buffer) {
buffer.append("eqReadRequest(mbean = \"");
buffer.append(pMBean);
buffer.append("\", attribute = \"");
buffer.append(pAttribute);
buffer.append("\")");
}
});
return null;
}
@Test
public void singlePost() throws IOException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp);
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream(HttpTestUtil.HEAP_MEMORY_POST_REQUEST);
JSONObject response = (JSONObject) handler.handlePostRequest("/jolokia",is,"utf-8",null);
assertTrue(response == resp);
}
@Test
public void doublePost() throws IOException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
JSONObject resp = new JSONObject();
expect(backend.handleRequest(isA(JmxReadRequest.class))).andReturn(resp).times(2);
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("[" + HttpTestUtil.HEAP_MEMORY_POST_REQUEST + "," + HttpTestUtil.HEAP_MEMORY_POST_REQUEST + "]");
JSONArray response = (JSONArray) handler.handlePostRequest("/jolokia", is, "utf-8", null);
assertEquals(response.size(),2);
assertTrue(response.get(0) == resp);
assertTrue(response.get(1) == resp);
}
@Test
public void preflightCheck() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(true);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
}
@Test
public void preflightCheckNegative() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(false);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertNull(ret.get("Access-Control-Allow-Origin"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void invalidJson() throws IOException {
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("{ bla;");
handler.handlePostRequest("/jolokia",is,"utf-8",null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void invalidJson2() throws IOException {
replay(backend);
InputStream is = HttpTestUtil.createServletInputStream("12");
handler.handlePostRequest("/jolokia",is,"utf-8",null);
}
@Test
public void requestErrorHandling() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Object[] exceptions = new Object[] {
new ReflectionException(new NullPointerException()), 404,500,
new InstanceNotFoundException(), 404, 500,
new MBeanException(new NullPointerException()), 500, 500,
new AttributeNotFoundException(), 404, 500,
new UnsupportedOperationException(), 500, 500,
new IOException(), 500, 500,
new IllegalArgumentException(), 400, 400,
new SecurityException(),403, 403,
new RuntimeMBeanException(new NullPointerException()), 500, 500
};
for (int i = 0; i < exceptions.length; i += 3) {
Exception e = (Exception) exceptions[i];
reset(backend);
expect(backend.isDebug()).andReturn(true).anyTimes();
backend.error(find("" + exceptions[i + 1]), EasyMock.<Throwable>anyObject());
backend.error(find("" + exceptions[i + 2]), EasyMock.<Throwable>anyObject());
expect(backend.handleRequest(EasyMock.<JmxRequest>anyObject())).andThrow(e);
replay(backend);
JSONObject resp = (JSONObject) handler.handleGetRequest("/jolokia",
"/read/java.lang:type=Memory/HeapMemoryUsage",null);
assertEquals(resp.get("status"),exceptions[i+1]);
resp = handler.handleThrowable(e);
assertEquals(resp.get("status"),exceptions[i+2],e.getClass().getName());
}
}
// ======================================================================================================
private LogHandler createDummyLogHandler() {
return new LogHandler() {
public void debug(String message) {
}
public void info(String message) {
}
public void error(String message, Throwable t) {
}
};
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_9 |
crossvul-java_data_bad_2028_0 | package io.hawt.web.plugin.karaf.terminal;
import io.hawt.system.Helpers;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.shell.console.jline.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Constructor;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class TerminalServlet extends HttpServlet {
public static final int TERM_WIDTH = 120;
public static final int TERM_HEIGHT = 39;
private final static Logger LOG = LoggerFactory.getLogger(TerminalServlet.class);
/**
* Pseudo class version ID to keep the IDE quite.
*/
private static final long serialVersionUID = 1L;
public CommandProcessor getCommandProcessor() {
return CommandProcessorHolder.getCommandProcessor();
}
public ThreadIO getThreadIO() {
return ThreadIOHolder.getThreadIO();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(response);
return;
}
session = request.getSession(true);
session.setAttribute("subject", subject);
} else {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
session.invalidate();
Helpers.doForbidden(response);
return;
}
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
}
public class SessionTerminal implements Runnable {
private Terminal terminal;
private Console console;
private PipedOutputStream in;
private PipedInputStream out;
private boolean closed;
public SessionTerminal(CommandProcessor commandProcessor, ThreadIO threadIO) throws IOException {
try {
this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT);
terminal.write("\u001b\u005B20\u0068"); // set newline mode on
in = new PipedOutputStream();
out = new PipedInputStream();
PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true);
Constructor ctr = Console.class.getConstructors()[0];
if (ctr.getParameterTypes().length <= 7) {
LOG.debug("Using old Karaf Console API");
// the old API does not have the threadIO parameter, so its only 7 parameters
console = (Console) ctr.newInstance(commandProcessor,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
} else {
LOG.debug("Using new Karaf Console API");
// use the new api directly which we compile against
console = new Console(commandProcessor,
threadIO,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
}
CommandSession session = console.getSession();
session.put("APPLICATION", System.getProperty("karaf.name", "root"));
session.put("USER", "karaf");
session.put("COLUMNS", Integer.toString(TERM_WIDTH));
session.put("LINES", Integer.toString(TERM_HEIGHT));
} catch (IOException e) {
LOG.info("Exception attaching to console", e);
throw e;
} catch (Exception e) {
LOG.info("Exception attaching to console", e);
throw (IOException) new IOException().initCause(e);
}
new Thread(console).start();
new Thread(this).start();
}
public boolean isClosed() {
return closed;
}
public String handle(String str, boolean forceDump) throws IOException {
try {
if (str != null && str.length() > 0) {
String d = terminal.pipe(str);
for (byte b : d.getBytes()) {
in.write(b);
}
in.flush();
}
} catch (IOException e) {
closed = true;
throw e;
}
try {
return terminal.dump(10, forceDump);
} catch (InterruptedException e) {
throw new InterruptedIOException(e.toString());
}
}
public void run() {
try {
for (; ; ) {
byte[] buf = new byte[8192];
int l = out.read(buf);
InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(buf, 0, l));
StringBuilder sb = new StringBuilder();
for (; ; ) {
int c = r.read();
if (c == -1) {
break;
}
sb.append((char) c);
}
if (sb.length() > 0) {
terminal.write(sb.toString());
}
String s = terminal.read();
if (s != null && s.length() > 0) {
for (byte b : s.getBytes()) {
in.write(b);
}
}
}
} catch (IOException e) {
closed = true;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2028_0 |
crossvul-java_data_good_3058_0 | /*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
* Tom Huybrechts, Vincent Latombe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.google.common.base.Predicate;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.*;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.SecurityRealm;
import hudson.security.UserMayOrMayNotExistException;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.RunList;
import hudson.util.XStream2;
import jenkins.model.IdStrategy;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithContextMenu;
import jenkins.security.ImpersonatingUserDetailsService;
import jenkins.security.LastGrantedAuthoritiesProperty;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Represents a user.
*
* <p>
* In Hudson, {@link User} objects are created in on-demand basis;
* for example, when a build is performed, its change log is computed
* and as a result commits from users who Hudson has never seen may be discovered.
* When this happens, new {@link User} object is created.
*
* <p>
* If the persisted record for an user exists, the information is loaded at
* that point, but if there's no such record, a fresh instance is created from
* thin air (this is where {@link UserPropertyDescriptor#newInstance(User)} is
* called to provide initial {@link UserProperty} objects.
*
* <p>
* Such newly created {@link User} objects will be simply GC-ed without
* ever leaving the persisted record, unless {@link User#save()} method
* is explicitly invoked (perhaps as a result of a browser submitting a
* configuration.)
*
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class User extends AbstractModelObject implements AccessControlled, DescriptorByNameOwner, Saveable, Comparable<User>, ModelObjectWithContextMenu {
/**
* The username of the 'unknown' user used to avoid null user references.
*/
private static final String UKNOWN_USERNAME = "unknown";
/**
* These usernames should not be used by real users logging into Jenkins. Therefore, we prevent
* users with these names from being saved.
*/
private static final String[] ILLEGAL_PERSISTED_USERNAMES = new String[]{ACL.ANONYMOUS_USERNAME,
ACL.SYSTEM_USERNAME, UKNOWN_USERNAME};
private transient final String id;
private volatile String fullName;
private volatile String description;
/**
* List of {@link UserProperty}s configured for this project.
*/
@CopyOnWrite
private volatile List<UserProperty> properties = new ArrayList<UserProperty>();
private User(String id, String fullName) {
this.id = id;
this.fullName = fullName;
load();
}
/**
* Returns the {@link jenkins.model.IdStrategy} for use with {@link User} instances. See
* {@link hudson.security.SecurityRealm#getUserIdStrategy()}
*
* @return the {@link jenkins.model.IdStrategy} for use with {@link User} instances.
* @since 1.566
*/
@Nonnull
public static IdStrategy idStrategy() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return IdStrategy.CASE_INSENSITIVE;
}
SecurityRealm realm = j.getSecurityRealm();
if (realm == null) {
return IdStrategy.CASE_INSENSITIVE;
}
return realm.getUserIdStrategy();
}
public int compareTo(User that) {
return idStrategy().compare(this.id, that.id);
}
/**
* Loads the other data from disk if it's available.
*/
private synchronized void load() {
properties.clear();
XmlFile config = getConfigFile();
try {
if(config.exists())
config.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
}
// remove nulls that have failed to load
for (Iterator<UserProperty> itr = properties.iterator(); itr.hasNext();) {
if(itr.next()==null)
itr.remove();
}
// allocate default instances if needed.
// doing so after load makes sure that newly added user properties do get reflected
for (UserPropertyDescriptor d : UserProperty.all()) {
if(getProperty(d.clazz)==null) {
UserProperty up = d.newInstance(this);
if(up!=null)
properties.add(up);
}
}
for (UserProperty p : properties)
p.setUser(this);
}
@Exported
public String getId() {
return id;
}
public @Nonnull String getUrl() {
return "user/"+Util.rawEncode(idStrategy().keyFor(id));
}
public @Nonnull String getSearchUrl() {
return "/user/"+Util.rawEncode(idStrategy().keyFor(id));
}
/**
* The URL of the user page.
*/
@Exported(visibility=999)
public @Nonnull String getAbsoluteUrl() {
return Jenkins.getInstance().getRootUrl()+getUrl();
}
/**
* Gets the human readable name of this user.
* This is configurable by the user.
*/
@Exported(visibility=999)
public @Nonnull String getFullName() {
return fullName;
}
/**
* Sets the human readable name of the user.
* If the input parameter is empty, the user's ID will be set.
*/
public void setFullName(String name) {
if(Util.fixEmptyAndTrim(name)==null) name=id;
this.fullName = name;
}
@Exported
public @CheckForNull String getDescription() {
return description;
}
/**
* Sets the description of the user.
* @since 1.609
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the user properties configured for this user.
*/
public Map<Descriptor<UserProperty>,UserProperty> getProperties() {
return Descriptor.toMap(properties);
}
/**
* Updates the user object by adding a property.
*/
public synchronized void addProperty(@Nonnull UserProperty p) throws IOException {
UserProperty old = getProperty(p.getClass());
List<UserProperty> ps = new ArrayList<UserProperty>(properties);
if(old!=null)
ps.remove(old);
ps.add(p);
p.setUser(this);
properties = ps;
save();
}
/**
* List of all {@link UserProperty}s exposed primarily for the remoting API.
*/
@Exported(name="property",inline=true)
public List<UserProperty> getAllProperties() {
return Collections.unmodifiableList(properties);
}
/**
* Gets the specific property, or null.
*/
public <T extends UserProperty> T getProperty(Class<T> clazz) {
for (UserProperty p : properties) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
/**
* Creates an {@link Authentication} object that represents this user.
*
* This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
* If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
* use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
* logged in.
*
* @throws UsernameNotFoundException
* If this user is not a valid user in the backend {@link SecurityRealm}.
* @since 1.419
*/
public @Nonnull Authentication impersonate() throws UsernameNotFoundException {
try {
UserDetails u = new ImpersonatingUserDetailsService(
Jenkins.getInstance().getSecurityRealm().getSecurityComponents().userDetails).loadUserByUsername(id);
return new UsernamePasswordAuthenticationToken(u.getUsername(), "", u.getAuthorities());
} catch (UserMayOrMayNotExistException e) {
// backend can't load information about other users. so use the stored information if available
} catch (UsernameNotFoundException e) {
// if the user no longer exists in the backend, we need to refuse impersonating this user
if (!ALLOW_NON_EXISTENT_USER_TO_LOGIN)
throw e;
} catch (DataAccessException e) {
// seems like it's in the same boat as UserMayOrMayNotExistException
}
// seems like a legitimate user we have no idea about. proceed with minimum access
return new UsernamePasswordAuthenticationToken(id, "",
new GrantedAuthority[]{SecurityRealm.AUTHENTICATED_AUTHORITY});
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
description = req.getParameter("description");
save();
rsp.sendRedirect("."); // go to the top page
}
/**
* Gets the fallback "unknown" user instance.
* <p>
* This is used to avoid null {@link User} instance.
*/
public static @Nonnull User getUnknown() {
return getById(UKNOWN_USERNAME, true);
}
/**
* Gets the {@link User} object by its id or full name.
*
* @param create
* If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
* @return Requested user. May be {@code null} if a user does not exist and
* {@code create} is false.
* @deprecated use {@link User#get(String, boolean, java.util.Map)}
*/
@Deprecated
public static @Nullable User get(String idOrFullName, boolean create) {
return get(idOrFullName, create, Collections.emptyMap());
}
/**
* Gets the {@link User} object by its id or full name.
*
* @param create
* If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
*
* @param context
* contextual environment this user idOfFullName was retrieved from,
* that can help resolve the user ID
*
* @return
* An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
public static @Nullable User get(String idOrFullName, boolean create, Map context) {
if(idOrFullName==null)
return null;
// sort resolvers by priority
List<CanonicalIdResolver> resolvers = new ArrayList<CanonicalIdResolver>(ExtensionList.lookup(CanonicalIdResolver.class));
Collections.sort(resolvers);
String id = null;
for (CanonicalIdResolver resolver : resolvers) {
id = resolver.resolveCanonicalId(idOrFullName, context);
if (id != null) {
LOGGER.log(Level.FINE, "{0} mapped {1} to {2}", new Object[] {resolver, idOrFullName, id});
break;
}
}
// DefaultUserCanonicalIdResolver will always return a non-null id if all other CanonicalIdResolver failed
if (id == null) {
throw new IllegalStateException("The user id should be always non-null thanks to DefaultUserCanonicalIdResolver");
}
return getOrCreate(id, idOrFullName, create);
}
/**
* Retrieve a user by its ID, and create a new one if requested.
* @return
* An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
private static @Nullable User getOrCreate(@Nonnull String id, @Nonnull String fullName, boolean create) {
String idkey = idStrategy().keyFor(id);
byNameLock.readLock().lock();
User u;
try {
u = byName.get(idkey);
} finally {
byNameLock.readLock().unlock();
}
final File configFile = getConfigFileFor(id);
if (!configFile.isFile() && !configFile.getParentFile().isDirectory()) {
// check for legacy users and migrate if safe to do so.
File[] legacy = getLegacyConfigFilesFor(id);
if (legacy != null && legacy.length > 0) {
for (File legacyUserDir : legacy) {
final XmlFile legacyXml = new XmlFile(XSTREAM, new File(legacyUserDir, "config.xml"));
try {
Object o = legacyXml.read();
if (o instanceof User) {
if (idStrategy().equals(id, legacyUserDir.getName()) && !idStrategy().filenameOf(legacyUserDir.getName())
.equals(legacyUserDir.getName())) {
if (!legacyUserDir.renameTo(configFile.getParentFile())) {
LOGGER.log(Level.WARNING, "Failed to migrate user record from {0} to {1}",
new Object[]{legacyUserDir, configFile.getParentFile()});
}
break;
}
} else {
LOGGER.log(Level.FINE, "Unexpected object loaded from {0}: {1}",
new Object[]{ legacyUserDir, o });
}
} catch (IOException e) {
LOGGER.log(Level.FINE, String.format("Exception trying to load user from {0}: {1}",
new Object[]{ legacyUserDir, e.getMessage() }), e);
}
}
}
}
if (u==null && (create || configFile.exists())) {
User tmp = new User(id, fullName);
User prev;
byNameLock.readLock().lock();
try {
prev = byName.putIfAbsent(idkey, u = tmp);
} finally {
byNameLock.readLock().unlock();
}
if (prev != null) {
u = prev; // if some has already put a value in the map, use it
if (LOGGER.isLoggable(Level.FINE) && !fullName.equals(prev.getFullName())) {
LOGGER.log(Level.FINE, "mismatch on fullName (‘" + fullName + "’ vs. ‘" + prev.getFullName() + "’) for ‘" + id + "’", new Throwable());
}
} else if (!id.equals(fullName) && !configFile.exists()) {
// JENKINS-16332: since the fullName may not be recoverable from the id, and various code may store the id only, we must save the fullName
try {
u.save();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}
return u;
}
/**
* Gets the {@link User} object by its id or full name.
* Use {@link #getById} when you know you have an ID.
*/
public static @Nonnull User get(String idOrFullName) {
return get(idOrFullName,true);
}
/**
* Gets the {@link User} object representing the currently logged-in user, or null
* if the current user is anonymous.
* @since 1.172
*/
public static @CheckForNull User current() {
return get(Jenkins.getAuthentication());
}
/**
* Gets the {@link User} object representing the supplied {@link Authentication} or
* {@code null} if the supplied {@link Authentication} is either anonymous or {@code null}
* @param a the supplied {@link Authentication} .
* @return a {@link User} object for the supplied {@link Authentication} or {@code null}
* @since 1.609
*/
public static @CheckForNull User get(@CheckForNull Authentication a) {
if(a == null || a instanceof AnonymousAuthenticationToken)
return null;
// Since we already know this is a name, we can just call getOrCreate with the name directly.
String id = a.getName();
return getById(id, true);
}
/**
* Gets the {@link User} object by its <code>id</code>
*
* @param id
* the id of the user to retrieve and optionally create if it does not exist.
* @param create
* If <code>true</code>, this method will never return <code>null</code> for valid input (by creating a
* new {@link User} object if none exists.) If <code>false</code>, this method will return
* <code>null</code> if {@link User} object with the given id doesn't exist.
* @return the a User whose id is <code>id</code>, or <code>null</code> if <code>create</code> is <code>false</code>
* and the user does not exist.
*/
public static @Nullable User getById(String id, boolean create) {
return getOrCreate(id, id, create);
}
private static volatile long lastScanned;
/**
* Gets all the users.
*/
public static @Nonnull Collection<User> getAll() {
final IdStrategy strategy = idStrategy();
if(System.currentTimeMillis() -lastScanned>10000) {
// occasionally scan the file system to check new users
// whether we should do this only once at start up or not is debatable.
// set this right away to avoid another thread from doing the same thing while we do this.
// having two threads doing the work won't cause race condition, but it's waste of time.
lastScanned = System.currentTimeMillis();
File[] subdirs = getRootDir().listFiles((FileFilter)DirectoryFileFilter.INSTANCE);
if(subdirs==null) return Collections.emptyList(); // shall never happen
for (File subdir : subdirs)
if(new File(subdir,"config.xml").exists()) {
String name = strategy.idFromFilename(subdir.getName());
User.getOrCreate(name, name, true);
}
lastScanned = System.currentTimeMillis();
}
byNameLock.readLock().lock();
ArrayList<User> r;
try {
r = new ArrayList<User>(byName.values());
} finally {
byNameLock.readLock().unlock();
}
Collections.sort(r,new Comparator<User>() {
public int compare(User o1, User o2) {
return strategy.compare(o1.getId(), o2.getId());
}
});
return r;
}
/**
* Reloads the configuration from disk.
*/
public static void reload() {
byNameLock.readLock().lock();
try {
for (User u : byName.values()) {
u.load();
}
} finally {
byNameLock.readLock().unlock();
}
}
/**
* Stop gap hack. Don't use it. To be removed in the trunk.
*/
public static void clear() {
byNameLock.writeLock().lock();
try {
byName.clear();
} finally {
byNameLock.writeLock().unlock();
}
}
/**
* Called when changing the {@link IdStrategy}.
* @since 1.566
*/
public static void rekey() {
final IdStrategy strategy = idStrategy();
byNameLock.writeLock().lock();
try {
for (Map.Entry<String, User> e : byName.entrySet()) {
String idkey = strategy.keyFor(e.getValue().id);
if (!idkey.equals(e.getKey())) {
// need to remap
byName.remove(e.getKey());
byName.putIfAbsent(idkey, e.getValue());
}
}
} finally {
byNameLock.writeLock().unlock();
}
}
/**
* Returns the user name.
*/
public @Nonnull String getDisplayName() {
return getFullName();
}
/** true if {@link AbstractBuild#hasParticipant} or {@link hudson.model.Cause.UserIdCause} */
private boolean relatedTo(@Nonnull AbstractBuild<?,?> b) {
if (b.hasParticipant(this)) {
return true;
}
for (Cause cause : b.getCauses()) {
if (cause instanceof Cause.UserIdCause) {
String userId = ((Cause.UserIdCause) cause).getUserId();
if (userId != null && idStrategy().equals(userId, getId())) {
return true;
}
}
}
return false;
}
/**
* Gets the list of {@link Build}s that include changes by this user,
* by the timestamp order.
*/
@WithBridgeMethods(List.class)
public @Nonnull RunList getBuilds() {
return new RunList<Run<?,?>>(Jenkins.getInstance().getAllItems(Job.class)).filter(new Predicate<Run<?,?>>() {
@Override public boolean apply(Run<?,?> r) {
return r instanceof AbstractBuild && relatedTo((AbstractBuild<?,?>) r);
}
});
}
/**
* Gets all the {@link AbstractProject}s that this user has committed to.
* @since 1.191
*/
public @Nonnull Set<AbstractProject<?,?>> getProjects() {
Set<AbstractProject<?,?>> r = new HashSet<AbstractProject<?,?>>();
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class))
if(p.hasParticipant(this))
r.add(p);
return r;
}
public @Override String toString() {
return fullName;
}
/**
* The file we save our configuration.
*/
protected final XmlFile getConfigFile() {
return new XmlFile(XSTREAM,getConfigFileFor(id));
}
private static final File getConfigFileFor(String id) {
return new File(getRootDir(), idStrategy().filenameOf(id) +"/config.xml");
}
private static final File[] getLegacyConfigFilesFor(final String id) {
return getRootDir().listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() && new File(pathname, "config.xml").isFile() && idStrategy().equals(
pathname.getName(), id);
}
});
}
/**
* Gets the directory where Hudson stores user information.
*/
private static File getRootDir() {
return new File(Jenkins.getInstance().getRootDir(), "users");
}
/**
* Is the ID allowed? Some are prohibited for security reasons. See SECURITY-166.
* <p/>
* Note that this is only enforced when saving. These users are often created
* via the constructor (and even listed on /asynchPeople), but our goal is to
* prevent anyone from logging in as these users. Therefore, we prevent
* saving a User with one of these ids.
*
* @return true if the username or fullname is valid
* @since 1.600
*/
public static boolean isIdOrFullnameAllowed(String id) {
for (String invalidId : ILLEGAL_PERSISTED_USERNAMES) {
if (id.equalsIgnoreCase(invalidId))
return false;
}
return true;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException, FormValidation {
if (! isIdOrFullnameAllowed(id)) {
throw FormValidation.error(Messages.User_IllegalUsername(id));
}
if (! isIdOrFullnameAllowed(fullName)) {
throw FormValidation.error(Messages.User_IllegalFullname(fullName));
}
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Deletes the data directory and removes this user from Hudson.
*
* @throws IOException
* if we fail to delete.
*/
public synchronized void delete() throws IOException {
final IdStrategy strategy = idStrategy();
byNameLock.readLock().lock();
try {
byName.remove(strategy.keyFor(id));
} finally {
byNameLock.readLock().unlock();
}
Util.deleteRecursive(new File(getRootDir(), strategy.filenameOf(id)));
}
/**
* Exposed remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Accepts submission from the configuration page.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(Jenkins.ADMINISTER);
JSONObject json = req.getSubmittedForm();
fullName = json.getString("fullName");
description = json.getString("description");
List<UserProperty> props = new ArrayList<UserProperty>();
int i = 0;
for (UserPropertyDescriptor d : UserProperty.all()) {
UserProperty p = getProperty(d.clazz);
JSONObject o = json.optJSONObject("userProperty" + (i++));
if (o!=null) {
if (p != null) {
p = p.reconfigure(req, o);
} else {
p = d.newInstance(req, o);
}
p.setUser(this);
}
if (p!=null)
props.add(p);
}
this.properties = props;
save();
FormApply.success(".").generateResponse(req,rsp,this);
}
/**
* Deletes this user from Hudson.
*/
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
if (idStrategy().equals(id, Jenkins.getAuthentication().getName())) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot delete self");
return;
}
delete();
rsp.sendRedirect2("../..");
}
public void doRssAll(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds(), Run.FEED_ADAPTER);
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
rss(req, rsp, " regression builds", getBuilds().regressionOnly(), Run.FEED_ADAPTER);
}
public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
final List<Run> lastBuilds = new ArrayList<Run>();
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
for (AbstractBuild<?,?> b = p.getLastBuild(); b != null; b = b.getPreviousBuild()) {
if (relatedTo(b)) {
lastBuilds.add(b);
break;
}
}
}
rss(req, rsp, " latest build", RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST);
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs, FeedAdapter adapter)
throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(), runs.newBuilds(), adapter, req, rsp);
}
/**
* Keyed by {@link User#id}. This map is used to ensure
* singleton-per-id semantics of {@link User} objects.
*
* The key needs to be generated by {@link IdStrategy#keyFor(String)}.
*/
@GuardedBy("byNameLock")
private static final ConcurrentMap<String,User> byName = new ConcurrentHashMap<String, User>();
/**
* This lock is used to guard access to the {@link #byName} map. Use
* {@link java.util.concurrent.locks.ReadWriteLock#readLock()} for normal access and
* {@link java.util.concurrent.locks.ReadWriteLock#writeLock()} for {@link #rekey()} or any other operation
* that requires operating on the map as a whole.
*/
private static final ReadWriteLock byNameLock = new ReentrantReadWriteLock();
/**
* Used to load/save user configuration.
*/
public static final XStream2 XSTREAM = new XStream2();
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
static {
XSTREAM.alias("user",User.class);
}
public ACL getACL() {
final ACL base = Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
// always allow a non-anonymous user full control of himself.
return new ACL() {
public boolean hasPermission(Authentication a, Permission permission) {
return (idStrategy().equals(a.getName(), id) && !(a instanceof AnonymousAuthenticationToken))
|| base.hasPermission(a, permission);
}
};
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* With ADMINISTER permission, can delete users with persisted data but can't delete self.
*/
public boolean canDelete() {
final IdStrategy strategy = idStrategy();
return hasPermission(Jenkins.ADMINISTER) && !strategy.equals(id, Jenkins.getAuthentication().getName())
&& new File(getRootDir(), strategy.filenameOf(id)).exists();
}
/**
* Checks for authorities (groups) associated with this user.
* If the caller lacks {@link Jenkins#ADMINISTER}, or any problems arise, returns an empty list.
* {@link SecurityRealm#AUTHENTICATED_AUTHORITY} and the username, if present, are omitted.
* @since 1.498
* @return a possibly empty list
*/
public @Nonnull List<String> getAuthorities() {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return Collections.emptyList();
}
List<String> r = new ArrayList<String>();
Authentication authentication;
try {
authentication = impersonate();
} catch (UsernameNotFoundException x) {
LOGGER.log(Level.FINE, "cannot look up authorities for " + id, x);
return Collections.emptyList();
}
for (GrantedAuthority a : authentication.getAuthorities()) {
if (a.equals(SecurityRealm.AUTHENTICATED_AUTHORITY)) {
continue;
}
String n = a.getAuthority();
if (n != null && !idStrategy().equals(n, id)) {
r.add(n);
}
}
Collections.sort(r, String.CASE_INSENSITIVE_ORDER);
return r;
}
public Descriptor getDescriptorByName(String className) {
return Jenkins.getInstance().getDescriptorByName(className);
}
public Object getDynamic(String token) {
for(Action action: getTransientActions()){
if(action.getUrlName().equals(token))
return action;
}
for(Action action: getPropertyActions()){
if(action.getUrlName().equals(token))
return action;
}
return null;
}
/**
* Return all properties that are also actions.
*
* @return the list can be empty but never null. read only.
*/
public List<Action> getPropertyActions() {
List<Action> actions = new ArrayList<Action>();
for (UserProperty userProp : getProperties().values()) {
if (userProp instanceof Action) {
actions.add((Action) userProp);
}
}
return Collections.unmodifiableList(actions);
}
/**
* Return all transient actions associated with this user.
*
* @return the list can be empty but never null. read only.
*/
public List<Action> getTransientActions() {
List<Action> actions = new ArrayList<Action>();
for (TransientUserActionFactory factory: TransientUserActionFactory.all()) {
actions.addAll(factory.createFor(this));
}
return Collections.unmodifiableList(actions);
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
return new ContextMenu().from(this,request,response);
}
public static abstract class CanonicalIdResolver extends AbstractDescribableImpl<CanonicalIdResolver> implements ExtensionPoint, Comparable<CanonicalIdResolver> {
/**
* context key for realm (domain) where idOrFullName has been retreived from.
* Can be used (for example) to distinguish ambiguous committer ID using the SCM URL.
* Associated Value is a {@link String}
*/
public static final String REALM = "realm";
public int compareTo(CanonicalIdResolver o) {
// reverse priority order
int i = getPriority();
int j = o.getPriority();
return i>j ? -1 : (i==j ? 0:1);
}
/**
* extract user ID from idOrFullName with help from contextual infos.
* can return <code>null</code> if no user ID matched the input
*/
public abstract @CheckForNull String resolveCanonicalId(String idOrFullName, Map<String, ?> context);
public int getPriority() {
return 1;
}
}
/**
* Resolve user ID from full name
*/
@Extension
public static class FullNameIdResolver extends CanonicalIdResolver {
@Override
public String resolveCanonicalId(String idOrFullName, Map<String, ?> context) {
for (User user : getAll()) {
if (idOrFullName.equals(user.getFullName())) return user.getId();
}
return null;
}
@Override
public int getPriority() {
return -1; // lower than default
}
}
/**
* Tries to verify if an ID is valid.
* If so, we do not want to even consider users who might have the same full name.
*/
@Extension
@Restricted(NoExternalUse.class)
public static class UserIDCanonicalIdResolver extends User.CanonicalIdResolver {
private static /* not final */ boolean SECURITY_243_FULL_DEFENSE = Boolean.parseBoolean(System.getProperty(User.class.getName() + ".SECURITY_243_FULL_DEFENSE", "true"));
private static final ThreadLocal<Boolean> resolving = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
@Override
public String resolveCanonicalId(String idOrFullName, Map<String, ?> context) {
User existing = getById(idOrFullName, false);
if (existing != null) {
return existing.getId();
}
if (SECURITY_243_FULL_DEFENSE) {
Jenkins j = Jenkins.getInstance();
if (j != null) {
if (!resolving.get()) {
resolving.set(true);
try {
return j.getSecurityRealm().loadUserByUsername(idOrFullName).getUsername();
} catch (UsernameNotFoundException x) {
LOGGER.log(Level.FINE, "not sure whether " + idOrFullName + " is a valid username or not", x);
} catch (DataAccessException x) {
LOGGER.log(Level.FINE, "could not look up " + idOrFullName, x);
} finally {
resolving.set(false);
}
}
}
}
return null;
}
@Override
public int getPriority() {
// should always come first so that ID that are ids get mapped correctly
return Integer.MAX_VALUE;
}
}
/**
* Jenkins now refuses to let the user login if he/she doesn't exist in {@link SecurityRealm},
* which was necessary to make sure users removed from the backend will get removed from the frontend.
* <p>
* Unfortunately this infringed some legitimate use cases of creating Jenkins-local users for
* automation purposes. This escape hatch switch can be enabled to resurrect that behaviour.
*
* JENKINS-22346.
*/
public static boolean ALLOW_NON_EXISTENT_USER_TO_LOGIN = Boolean.getBoolean(User.class.getName()+".allowNonExistentUserToLogin");
/**
* Jenkins historically created a (usually) ephemeral user record when an user with Overall/Administer permission
* accesses a /user/arbitraryName URL.
* <p>
* Unfortunately this constitutes a CSRF vulnerability, as malicious users can make admins create arbitrary numbers
* of ephemeral user records, so the behavior was changed in Jenkins 2.TODO / 2.32.2.
* <p>
* As some users may be relying on the previous behavior, setting this to true restores the previous behavior. This
* is not recommended.
*
* SECURITY-406.
*/
// TODO 2.4+ SystemProperties
@Restricted(NoExternalUse.class)
public static boolean ALLOW_USER_CREATION_VIA_URL = Boolean.getBoolean(User.class.getName() + ".allowUserCreationViaUrl");
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_3058_0 |
crossvul-java_data_bad_2031_7 | package org.jolokia.backend;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.IOException;
import java.util.Map;
import javax.management.*;
import org.jolokia.backend.executor.NotChangedException;
import org.jolokia.config.ConfigKey;
import org.jolokia.config.Configuration;
import org.jolokia.converter.Converters;
import org.jolokia.detector.ServerHandle;
import org.jolokia.request.JmxRequest;
import org.jolokia.request.JmxRequestBuilder;
import org.jolokia.restrictor.Restrictor;
import org.jolokia.util.*;
import org.json.simple.JSONObject;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author roland
* @since Jun 15, 2010
*/
public class BackendManagerTest {
Configuration config;
private LogHandler log = new LogHandler.StdoutLogHandler(true);
@BeforeTest
public void setup() {
config = new Configuration(ConfigKey.AGENT_ID,"test");
}
@Test
public void simpleRead() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DEBUG,"true",ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory")
.attribute("HeapMemoryUsage")
.build();
JSONObject ret = backendManager.handleRequest(req);
assertTrue((Long) ((Map) ret.get("value")).get("used") > 0);
backendManager.destroy();
}
@Test
public void notChanged() throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.LIST).build();
JSONObject ret = backendManager.handleRequest(req);
assertEquals(ret.get("status"),304);
backendManager.destroy();
}
@Test
public void lazyInit() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
BackendManager backendManager = new BackendManager(config, log, null, true /* Lazy Init */ );
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory")
.attribute("HeapMemoryUsage")
.build();
JSONObject ret = backendManager.handleRequest(req);
assertTrue((Long) ((Map) ret.get("value")).get("used") > 0);
backendManager.destroy();
}
@Test
public void requestDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
backendManager.handleRequest(req);
assertTrue(RequestDispatcherTest.called);
backendManager.destroy();
}
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*invalid constructor.*")
public void requestDispatcherWithWrongDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherWrong.class.getName(),ConfigKey.AGENT_ID,"test");
new BackendManager(config,log);
}
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*blub.bla.Dispatcher.*")
public void requestDispatcherWithUnkownDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,"blub.bla.Dispatcher",ConfigKey.AGENT_ID,"test");
new BackendManager(config,log);
}
@Test
public void debugging() {
RecordingLogHandler lhandler = new RecordingLogHandler();
BackendManager backendManager = new BackendManager(config,lhandler);
lhandler.error = 0;
lhandler.debug = 0;
lhandler.info = 0;
backendManager.debug("test");
assertEquals(lhandler.debug,1);
backendManager.error("test",new Exception());
assertEquals(lhandler.error,1);
backendManager.info("test");
assertEquals(lhandler.info,1);
backendManager.destroy();
}
@Test
public void defaultConfig() {
Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config,log);
backendManager.destroy();
}
@Test
public void doubleInit() {
BackendManager b1 = new BackendManager(config,log);
BackendManager b2 = new BackendManager(config,log);
b2.destroy();
b1.destroy();
}
@Test
public void remoteAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1"));
backendManager.destroy();
}
@Test
public void corsAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isCorsAccessAllowed("http://bla.com"));
backendManager.destroy();
}
@Test
public void convertError() throws MalformedObjectNameException {
BackendManager backendManager = new BackendManager(config,log);
Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb"));
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);
assertTrue(!jsonError.containsKey("stackTrace"));
assertEquals(jsonError.get("message"),"Hans");
assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb");
backendManager.destroy();
}
// =========================================================================================
static class RequestDispatcherTest implements RequestDispatcher {
static boolean called = false;
public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {
assertNotNull(pConverters);
assertNotNull(pRestrictor);
}
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
called = true;
if (pJmxReq.getType() == RequestType.READ) {
return new JSONObject();
} else if (pJmxReq.getType() == RequestType.WRITE) {
return "faultyFormat";
} else if (pJmxReq.getType() == RequestType.LIST) {
throw new NotChangedException(pJmxReq);
}
return null;
}
public boolean canHandle(JmxRequest pJmxRequest) {
return true;
}
public boolean useReturnValueWithPath(JmxRequest pJmxRequest) {
return false;
}
}
// ========================================================
static class RequestDispatcherWrong implements RequestDispatcher {
// No special constructor --> fail
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException {
return null;
}
public boolean canHandle(JmxRequest pJmxRequest) {
return false;
}
public boolean useReturnValueWithPath(JmxRequest pJmxRequest) {
return false;
}
}
private class RecordingLogHandler implements LogHandler {
int debug = 0;
int info = 0;
int error = 0;
public void debug(String message) {
debug++;
}
public void info(String message) {
info++;
}
public void error(String message, Throwable t) {
error++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_7 |
crossvul-java_data_good_5842_0 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.projectforge.core.Configuration;
import org.projectforge.core.ConfigurationDO;
import org.projectforge.database.InitDatabaseDao;
import org.projectforge.user.UserDao;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.CsrfTokenHandler;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.MaxLengthTextField;
import org.projectforge.web.wicket.components.RequiredMaxLengthTextField;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.components.TimeZonePanel;
import org.projectforge.web.wicket.flowlayout.DivPanel;
import org.projectforge.web.wicket.flowlayout.DivType;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.InputPanel;
import org.projectforge.web.wicket.flowlayout.ParTextPanel;
import org.projectforge.web.wicket.flowlayout.PasswordPanel;
import org.projectforge.web.wicket.flowlayout.RadioGroupPanel;
public class SetupForm extends AbstractForm<SetupForm, SetupPage>
{
private static final long serialVersionUID = -277853572580468505L;
private static final String MAGIC_PASSWORD = "******";
@SpringBean(name = "userDao")
private UserDao userDao;
private final SetupTarget setupMode = SetupTarget.TEST_DATA;
private final TimeZone timeZone = TimeZone.getDefault();
private String sysopEMail;
private String feedbackEMail;
private String calendarDomain;
private final String adminUsername = InitDatabaseDao.DEFAULT_ADMIN_USER;
// @SuppressWarnings("unused")
// private String organization;
@SuppressWarnings("unused")
private String password;
@SuppressWarnings("unused")
private String passwordRepeat;
private String encryptedPassword;
/**
* Cross site request forgery token.
*/
private final CsrfTokenHandler csrfTokenHandler;
public SetupForm(final SetupPage parentPage)
{
super(parentPage, "setupform");
csrfTokenHandler = new CsrfTokenHandler(this);
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
final GridBuilder gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newFormHeading(getString("administration.setup.heading"));
final DivPanel panel = gridBuilder.getPanel();
panel.add(new ParTextPanel(panel.newChildId(), getString("administration.setup.heading.subtitle")));
{
// RadioChoice mode
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.setup.target"));
final DivPanel radioPanel = new DivPanel(fs.newChildId(), DivType.RADIOBOX);
fs.add(radioPanel);
fs.setLabelFor(radioPanel);
final RadioGroupPanel<SetupTarget> radioGroup = new RadioGroupPanel<SetupTarget>(radioPanel.newChildId(), "setuptarget",
new PropertyModel<SetupTarget>(this, "setupMode"));
radioPanel.add(radioGroup);
for (final SetupTarget target : SetupTarget.values()) {
radioGroup.add(new Model<SetupTarget>(target), getString(target.getI18nKey()), getString(target.getI18nKey() + ".tooltip"));
}
}
// final RequiredMaxLengthTextField organizationField = new RequiredMaxLengthTextField(this, "organization", getString("organization"),
// new PropertyModel<String>(this, "organization"), 100);
// add(organizationField);
{
// User name
final FieldsetPanel fs = gridBuilder.newFieldset(getString("username"));
fs.add(new RequiredMaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "adminUsername"), 100));
}
final PasswordTextField passwordField = new PasswordTextField(PasswordPanel.WICKET_ID, new PropertyModel<String>(this, "password")) {
@Override
protected void onComponentTag(final ComponentTag tag)
{
super.onComponentTag(tag);
if (encryptedPassword == null) {
tag.put("value", "");
} else if (StringUtils.isEmpty(getConvertedInput()) == false) {
tag.put("value", MAGIC_PASSWORD);
}
}
};
{
// Password
final FieldsetPanel fs = gridBuilder.newFieldset(getString("password"));
passwordField.setRequired(true); // No setReset(true), otherwise uploading and re-entering passwords is a real pain.
fs.add(passwordField);
WicketUtils.setFocus(passwordField);
}
{
// Password repeat
final FieldsetPanel fs = gridBuilder.newFieldset(getString("passwordRepeat"));
final PasswordTextField passwordRepeatField = new PasswordTextField(PasswordPanel.WICKET_ID, new PropertyModel<String>(this,
"passwordRepeat")) {
@Override
protected void onComponentTag(final ComponentTag tag)
{
super.onComponentTag(tag);
if (encryptedPassword == null) {
tag.put("value", "");
} else if (StringUtils.isEmpty(getConvertedInput()) == false) {
tag.put("value", MAGIC_PASSWORD);
}
}
};
passwordRepeatField.setRequired(true); // No setReset(true), otherwise uploading and re-entering passwords is a real pain.
passwordRepeatField.add(new IValidator<String>() {
@Override
public void validate(final IValidatable<String> validatable)
{
final String input = validatable.getValue();
final String passwordInput = passwordField.getConvertedInput();
if (StringUtils.equals(input, passwordInput) == false) {
passwordRepeatField.error(getString("user.error.passwordAndRepeatDoesNotMatch"));
encryptedPassword = null;
return;
}
if (MAGIC_PASSWORD.equals(passwordInput) == false || encryptedPassword == null) {
final String errorMsgKey = userDao.checkPasswordQuality(passwordInput);
if (errorMsgKey != null) {
encryptedPassword = null;
passwordField.error(getString(errorMsgKey));
} else {
encryptedPassword = userDao.encryptPassword(passwordInput);
}
}
}
});
fs.add(passwordRepeatField);
}
{
// Time zone
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.timezone"));
final TimeZonePanel timeZone = new TimeZonePanel(fs.newChildId(), new PropertyModel<TimeZone>(this, "timeZone"));
fs.setLabelFor(timeZone);
fs.add(timeZone);
fs.addHelpIcon(getString("administration.configuration.param.timezone.description"));
}
{
// Calendar domain
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.calendarDomain"));
final RequiredMaxLengthTextField textField = new RequiredMaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this,
"calendarDomain"), ConfigurationDO.PARAM_LENGTH);
fs.add(textField);
textField.add(new IValidator<String>() {
@Override
public void validate(final IValidatable<String> validatable)
{
if (Configuration.isDomainValid(validatable.getValue()) == false) {
textField.error(getString("validation.error.generic"));
}
}
});
fs.addHelpIcon(getString("administration.configuration.param.calendarDomain.description"));
}
{
// E-Mail sysops
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.systemAdministratorEMail.label"),
getString("email"));
fs.add(new MaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "sysopEMail"), ConfigurationDO.PARAM_LENGTH));
fs.addHelpIcon(getString("administration.configuration.param.systemAdministratorEMail.description"));
}
{
// E-Mail sysops
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.feedbackEMail.label"),
getString("email"));
fs.add(new MaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "feedbackEMail"), ConfigurationDO.PARAM_LENGTH));
fs.addHelpIcon(getString("administration.configuration.param.feedbackEMail.description"));
}
final RepeatingView actionButtons = new RepeatingView("buttons");
add(actionButtons);
{
final Button finishButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("finish")) {
@Override
public final void onSubmit()
{
csrfTokenHandler.onSubmit();
parentPage.finishSetup();
}
};
final SingleButtonPanel finishButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), finishButton,
getString("administration.setup.finish"), SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(finishButtonPanel);
setDefaultButton(finishButton);
}
}
@Override
protected void onSubmit()
{
super.onSubmit();
csrfTokenHandler.onSubmit();
}
public SetupTarget getSetupMode()
{
return setupMode;
}
public TimeZone getTimeZone()
{
return timeZone;
}
/**
* @return the calendarDomain
*/
public String getCalendarDomain()
{
return calendarDomain;
}
public String getSysopEMail()
{
return sysopEMail;
}
public String getFeedbackEMail()
{
return feedbackEMail;
}
public String getEncryptedPassword()
{
return encryptedPassword;
}
public String getAdminUsername()
{
return adminUsername;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_5842_0 |
crossvul-java_data_good_2028_0 | package io.hawt.web.plugin.karaf.terminal;
import io.hawt.system.Helpers;
import io.hawt.web.LoginTokenServlet;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.shell.console.jline.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class TerminalServlet extends HttpServlet {
public static final int TERM_WIDTH = 120;
public static final int TERM_HEIGHT = 39;
private final static Logger LOG = LoggerFactory.getLogger(TerminalServlet.class);
/**
* Pseudo class version ID to keep the IDE quite.
*/
private static final long serialVersionUID = 1L;
public CommandProcessor getCommandProcessor() {
return CommandProcessorHolder.getCommandProcessor();
}
public ThreadIO getThreadIO() {
return ThreadIOHolder.getThreadIO();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
String token = request.getHeader(LoginTokenServlet.LOGIN_TOKEN);
if (token == null || session == null) {
Helpers.doForbidden(response);
return;
}
String sessionToken = (String) session.getAttribute(LoginTokenServlet.LOGIN_TOKEN);
if (!token.equals(sessionToken)) {
Helpers.doForbidden(response);
return;
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
}
public class SessionTerminal implements Runnable {
private Terminal terminal;
private Console console;
private PipedOutputStream in;
private PipedInputStream out;
private boolean closed;
public SessionTerminal(CommandProcessor commandProcessor, ThreadIO threadIO) throws IOException {
try {
this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT);
terminal.write("\u001b\u005B20\u0068"); // set newline mode on
in = new PipedOutputStream();
out = new PipedInputStream();
PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true);
Constructor ctr = Console.class.getConstructors()[0];
if (ctr.getParameterTypes().length <= 7) {
LOG.debug("Using old Karaf Console API");
// the old API does not have the threadIO parameter, so its only 7 parameters
console = (Console) ctr.newInstance(commandProcessor,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
} else {
LOG.debug("Using new Karaf Console API");
// use the new api directly which we compile against
console = new Console(commandProcessor,
threadIO,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
}
CommandSession session = console.getSession();
session.put("APPLICATION", System.getProperty("karaf.name", "root"));
session.put("USER", "karaf");
session.put("COLUMNS", Integer.toString(TERM_WIDTH));
session.put("LINES", Integer.toString(TERM_HEIGHT));
} catch (IOException e) {
LOG.info("Exception attaching to console", e);
throw e;
} catch (Exception e) {
LOG.info("Exception attaching to console", e);
throw (IOException) new IOException().initCause(e);
}
new Thread(console).start();
new Thread(this).start();
}
public boolean isClosed() {
return closed;
}
public String handle(String str, boolean forceDump) throws IOException {
try {
if (str != null && str.length() > 0) {
String d = terminal.pipe(str);
for (byte b : d.getBytes()) {
in.write(b);
}
in.flush();
}
} catch (IOException e) {
closed = true;
throw e;
}
try {
return terminal.dump(10, forceDump);
} catch (InterruptedException e) {
throw new InterruptedIOException(e.toString());
}
}
public void run() {
try {
for (; ; ) {
byte[] buf = new byte[8192];
int l = out.read(buf);
InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(buf, 0, l));
StringBuilder sb = new StringBuilder();
for (; ; ) {
int c = r.read();
if (c == -1) {
break;
}
sb.append((char) c);
}
if (sb.length() > 0) {
terminal.write(sb.toString());
}
String s = terminal.read();
if (s != null && s.length() > 0) {
for (byte b : s.getBytes()) {
in.write(b);
}
}
}
} catch (IOException e) {
closed = true;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2028_0 |
crossvul-java_data_bad_2028_5 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2028_5 |
crossvul-java_data_bad_5842_11 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.mobile;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.projectforge.core.AbstractBaseDO;
import org.projectforge.web.wicket.mobileflowlayout.MobileGridBuilder;
public abstract class AbstractMobileEditForm<O extends AbstractBaseDO< ? >, P extends AbstractMobileEditPage< ? , ? , ? >> extends
AbstractMobileForm<O, P>
{
private static final long serialVersionUID = 1836099012618517190L;
protected O data;
protected MobileGridBuilder gridBuilder;
public AbstractMobileEditForm(final P parentPage, final O data)
{
super(parentPage);
this.data = data;
}
public O getData()
{
return this.data;
}
public void setData(final O data)
{
this.data = data;
}
public boolean isNew()
{
return this.data == null || this.data.getId() == null;
}
@SuppressWarnings("serial")
protected void init()
{
add(new FeedbackPanel("feedback").setOutputMarkupId(true));
final SubmitLink submitButton = new SubmitLink("submitButton") {
@Override
public final void onSubmit()
{
parentPage.save();
}
};
final RepeatingView flowform = new RepeatingView("flowform");
add(flowform);
gridBuilder = newGridBuilder(flowform);
add(submitButton);
if (isNew() == true) {
submitButton.add(new Label("label", getString("create")));
} else {
submitButton.add(new Label("label", getString("update")));
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_11 |
crossvul-java_data_good_2031_1 | package org.jolokia.http;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.management.RuntimeMBeanException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jolokia.backend.BackendManager;
import org.jolokia.config.*;
import org.jolokia.discovery.DiscoveryMulticastResponder;
import org.jolokia.restrictor.*;
import org.jolokia.util.*;
import org.json.simple.JSONAware;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Agent servlet which connects to a local JMX MBeanServer for
* JMX operations.
*
* <p>
* It uses a REST based approach which translates a GET Url into a
* request. See the <a href="http://www.jolokia.org/reference/index.html">reference documentation</a>
* for a detailed description of this servlet's features.
* </p>
*
* @author roland@jolokia.org
* @since Apr 18, 2009
*/
public class AgentServlet extends HttpServlet {
private static final long serialVersionUID = 42L;
// POST- and GET- HttpRequestHandler
private ServletRequestHandler httpGetHandler, httpPostHandler;
// Backend dispatcher
private BackendManager backendManager;
// Used for logging
private LogHandler logHandler;
// Request handler for parsing request parameters and building up a response
private HttpRequestHandler requestHandler;
// Restrictor to use as given in the constructor
private Restrictor restrictor;
// Mime type used for returning the answer
private String configMimeType;
// Listen for discovery request (if switched on)
private DiscoveryMulticastResponder discoveryMulticastResponder;
// If discovery multicast is enabled and URL should be initialized by request
private boolean initAgentUrlFromRequest = false;
/**
* No argument constructor, used e.g. by an servlet
* descriptor when creating the servlet out of web.xml
*/
public AgentServlet() {
this(null);
}
/**
* Constructor taking a restrictor to use
*
* @param pRestrictor restrictor to use or <code>null</code> if the restrictor
* should be created in the default way ({@link #createRestrictor(String)})
*/
public AgentServlet(Restrictor pRestrictor) {
restrictor = pRestrictor;
}
/**
* Get the installed log handler
*
* @return loghandler used for logging.
*/
protected LogHandler getLogHandler() {
return logHandler;
}
/**
* Create a restrictor restrictor to use. By default, a policy file
* is looked up (with the URL given by the init parameter {@link ConfigKey#POLICY_LOCATION}
* or "/jolokia-access.xml" by default) and if not found an {@link AllowAllRestrictor} is
* used by default. This method is called during the {@link #init(ServletConfig)} when initializing
* the subsystems and can be overridden for custom restrictor creation.
*
* @param pLocation location to lookup the restrictor
* @return the restrictor to use.
*/
protected Restrictor createRestrictor(String pLocation) {
LogHandler log = getLogHandler();
try {
Restrictor newRestrictor = RestrictorFactory.lookupPolicyRestrictor(pLocation);
if (newRestrictor != null) {
log.info("Using access restrictor " + pLocation);
return newRestrictor;
} else {
log.info("No access restrictor found at " + pLocation + ", access to all MBeans is allowed");
return new AllowAllRestrictor();
}
} catch (IOException e) {
log.error("Error while accessing access restrictor at " + pLocation +
". Denying all access to MBeans for security reasons. Exception: " + e, e);
return new DenyAllRestrictor();
}
}
/**
* Initialize the backend systems, the log handler and the restrictor. A subclass can tune
* this step by overriding {@link #createRestrictor(String)} and {@link #createLogHandler(ServletConfig, boolean)}
*
* @param pServletConfig servlet configuration
*/
@Override
public void init(ServletConfig pServletConfig) throws ServletException {
super.init(pServletConfig);
Configuration config = initConfig(pServletConfig);
// Create a log handler early in the lifecycle, but not too early
String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS);
logHandler = logHandlerClass != null ?
(LogHandler) ClassUtil.newInstance(logHandlerClass) :
createLogHandler(pServletConfig,Boolean.valueOf(config.get(ConfigKey.DEBUG)));
// Different HTTP request handlers
httpGetHandler = newGetHttpRequestHandler();
httpPostHandler = newPostHttpRequestHandler();
if (restrictor == null) {
restrictor = createRestrictor(config.get(ConfigKey.POLICY_LOCATION));
} else {
logHandler.info("Using custom access restriction provided by " + restrictor);
}
configMimeType = config.get(ConfigKey.MIME_TYPE);
backendManager = new BackendManager(config,logHandler, restrictor);
requestHandler = new HttpRequestHandler(config,backendManager,logHandler);
initDiscoveryMulticast(config);
}
private void initDiscoveryMulticast(Configuration pConfig) {
String url = findAgentUrl(pConfig);
if (url != null || listenForDiscoveryMcRequests(pConfig)) {
if (url == null) {
initAgentUrlFromRequest = true;
} else {
initAgentUrlFromRequest = false;
backendManager.getAgentDetails().updateAgentParameters(url, null);
}
try {
discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager,restrictor,logHandler);
discoveryMulticastResponder.start();
} catch (IOException e) {
logHandler.error("Cannot start discovery multicast handler: " + e,e);
}
}
}
// Try to find an URL for system props or config
private String findAgentUrl(Configuration pConfig) {
// System property has precedence
String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
if (url == null) {
url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
if (url == null) {
url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
}
}
return NetworkUtil.replaceExpression(url);
}
// For war agent needs to be switched on
private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
// Check for system props, system env and agent config
boolean sysProp = System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
return sysProp || env || config;
}
/**
* Create a log handler using this servlet's logging facility for logging. This method can be overridden
* to provide a custom log handler. This method is called before {@link #createRestrictor(String)} so the log handler
* can already be used when building up the restrictor.
*
* @return a default log handler
* @param pServletConfig servlet config from where to get information to build up the log handler
* @param pDebug whether to print out debug information.
*/
protected LogHandler createLogHandler(ServletConfig pServletConfig, final boolean pDebug) {
return new LogHandler() {
/** {@inheritDoc} */
public void debug(String message) {
if (pDebug) {
log(message);
}
}
/** {@inheritDoc} */
public void info(String message) {
log(message);
}
/** {@inheritDoc} */
public void error(String message, Throwable t) {
log(message,t);
}
};
}
/** {@inheritDoc} */
@Override
public void destroy() {
backendManager.destroy();
if (discoveryMulticastResponder != null) {
discoveryMulticastResponder.stop();
discoveryMulticastResponder = null;
}
super.destroy();
}
/** {@inheritDoc} */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handle(httpGetHandler,req, resp);
}
/** {@inheritDoc} */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handle(httpPostHandler,req,resp);
}
/**
* OPTION requests are treated as CORS preflight requests
*
* @param req the original request
* @param resp the response the answer are written to
* */
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String,String> responseHeaders =
requestHandler.handleCorsPreflightRequest(
req.getHeader("Origin"),
req.getHeader("Access-Control-Request-Headers"));
for (Map.Entry<String,String> entry : responseHeaders.entrySet()) {
resp.setHeader(entry.getKey(),entry.getValue());
}
}
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" })
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
JSONAware json = null;
try {
// Check access policy
requestHandler.checkAccess(pReq.getRemoteHost(), pReq.getRemoteAddr(),
getOriginOrReferer(pReq));
// Remember the agent URL upon the first request. Needed for discovery
updateAgentUrlIfNeeded(pReq);
// Dispatch for the proper HTTP request method
json = pReqHandler.handleRequest(pReq,pResp);
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
setCorsHeader(pReq, pResp);
String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
String answer = json != null ?
json.toJSONString() :
requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
if (callback != null) {
// Send a JSONP response
sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
} else {
sendResponse(pResp, getMimeType(pReq),answer);
}
}
}
private String getOriginOrReferer(HttpServletRequest pReq) {
String origin = pReq.getHeader("Origin");
if (origin == null) {
origin = pReq.getHeader("Referer");
}
return origin != null ? origin.replaceAll("[\\n\\r]*","") : null;
}
// Update the agent URL in the agent details if not already done
private void updateAgentUrlIfNeeded(HttpServletRequest pReq) {
// Lookup the Agent URL if needed
if (initAgentUrlFromRequest) {
updateAgentUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()), extractServletPath(pReq),pReq.getAuthType() != null);
initAgentUrlFromRequest = false;
}
}
private String extractServletPath(HttpServletRequest pReq) {
return pReq.getRequestURI().substring(0,pReq.getContextPath().length());
}
// Update the URL in the AgentDetails
private void updateAgentUrl(String pRequestUrl, String pServletPath, boolean pIsAuthenticated) {
String url = getBaseUrl(pRequestUrl, pServletPath);
backendManager.getAgentDetails().updateAgentParameters(url,pIsAuthenticated);
}
// Strip off everything unneeded
private String getBaseUrl(String pUrl, String pServletPath) {
String sUrl;
try {
URL url = new URL(pUrl);
String host = getIpIfPossible(url.getHost());
sUrl = new URL(url.getProtocol(),host,url.getPort(),pServletPath).toExternalForm();
} catch (MalformedURLException exp) {
sUrl = plainReplacement(pUrl, pServletPath);
}
return sUrl;
}
// Check for an IP, since this seems to be safer to return then a plain name
private String getIpIfPossible(String pHost) {
try {
InetAddress address = InetAddress.getByName(pHost);
return address.getHostAddress();
} catch (UnknownHostException e) {
return pHost;
}
}
// Fallback used if URL creation didnt work
private String plainReplacement(String pUrl, String pServletPath) {
int idx = pUrl.lastIndexOf(pServletPath);
String url;
if (idx != -1) {
url = pUrl.substring(0,idx) + pServletPath;
} else {
url = pUrl;
}
return url;
}
// Set an appropriate CORS header if requested and if allowed
private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
if (origin != null) {
pResp.setHeader("Access-Control-Allow-Origin", origin);
pResp.setHeader("Access-Control-Allow-Credentials","true");
}
}
// Extract mime type for response (if not JSONP)
private String getMimeType(HttpServletRequest pReq) {
String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
if (requestMimeType != null) {
return requestMimeType;
}
return configMimeType;
}
private interface ServletRequestHandler {
/**
* Handle a request and return the answer as a JSON structure
* @param pReq request arrived
* @param pResp response to return
* @return the JSON representation for the answer
* @throws IOException if handling of an input or output stream failed
*/
JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
throws IOException;
}
// factory method for POST request handler
private ServletRequestHandler newPostHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
throws IOException {
String encoding = pReq.getCharacterEncoding();
InputStream is = pReq.getInputStream();
return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq));
}
};
}
// factory method for GET request handler
private ServletRequestHandler newGetHttpRequestHandler() {
return new ServletRequestHandler() {
/** {@inheritDoc} */
public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) {
return requestHandler.handleGetRequest(pReq.getRequestURI(),pReq.getPathInfo(), getParameterMap(pReq));
}
};
}
// =======================================================================
// Get parameter map either directly from an Servlet 2.4 compliant implementation
// or by looking it up explictely (thanks to codewax for the patch)
private Map<String, String[]> getParameterMap(HttpServletRequest pReq){
try {
// Servlet 2.4 API
return pReq.getParameterMap();
} catch (UnsupportedOperationException exp) {
// Thrown by 'pseudo' 2.4 Servlet API implementations which fake a 2.4 API
// As a service for the parameter map is build up explicitely
Map<String, String[]> ret = new HashMap<String, String[]>();
Enumeration params = pReq.getParameterNames();
while (params.hasMoreElements()) {
String param = (String) params.nextElement();
ret.put(param, pReq.getParameterValues(param));
}
return ret;
}
}
// Examines servlet config and servlet context for configuration parameters.
// Configuration from the servlet context overrides servlet parameters defined in web.xml
Configuration initConfig(ServletConfig pConfig) {
Configuration config = new Configuration(
ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(),"servlet"));
// From ServletContext ....
config.updateGlobalConfiguration(new ServletConfigFacade(pConfig));
// ... and ServletConfig
config.updateGlobalConfiguration(new ServletContextFacade(getServletContext()));
// Set type last and overwrite anything written
config.updateGlobalConfiguration(Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(),"servlet"));
return config;
}
private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt) throws IOException {
setContentType(pResp, pContentType);
pResp.setStatus(200);
setNoCacheHeaders(pResp);
PrintWriter writer = pResp.getWriter();
writer.write(pJsonTxt);
}
private void setNoCacheHeaders(HttpServletResponse pResp) {
pResp.setHeader("Cache-Control", "no-cache");
pResp.setHeader("Pragma","no-cache");
// Check for a date header and set it accordingly to the recommendations of
// RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21)
//
// "To mark a response as "already expired," an origin server sends an
// Expires date that is equal to the Date header value. (See the rules
// for expiration calculations in section 13.2.4.)"
//
// See also #71
long now = System.currentTimeMillis();
pResp.setDateHeader("Date",now);
// 1h in the past since it seems, that some servlet set the date header on their
// own so that it cannot be guaranteed that these headers are really equals.
// It happened on Tomcat that Date: was finally set *before* Expires: in the final
// answers some times which seems to be an implementation peculiarity from Tomcat
pResp.setDateHeader("Expires",now - 3600000);
}
private void setContentType(HttpServletResponse pResp, String pContentType) {
boolean encodingDone = false;
try {
pResp.setCharacterEncoding("utf-8");
pResp.setContentType(pContentType);
encodingDone = true;
}
catch (NoSuchMethodError error) { /* Servlet 2.3 */ }
catch (UnsupportedOperationException error) { /* Equinox HTTP Service */ }
if (!encodingDone) {
// For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand
pResp.setContentType(pContentType + "; charset=utf-8");
}
}
// =======================================================================================
// Helper classes for extracting configuration from servlet classes
// Implementation for the ServletConfig
private static final class ServletConfigFacade implements ConfigExtractor {
private final ServletConfig config;
private ServletConfigFacade(ServletConfig pConfig) {
config = pConfig;
}
/** {@inheritDoc} */
public Enumeration getNames() {
return config.getInitParameterNames();
}
/** {@inheritDoc} */
public String getParameter(String pName) {
return config.getInitParameter(pName);
}
}
// Implementation for ServletContextFacade
private static final class ServletContextFacade implements ConfigExtractor {
private final ServletContext servletContext;
private ServletContextFacade(ServletContext pServletContext) {
servletContext = pServletContext;
}
/** {@inheritDoc} */
public Enumeration getNames() {
return servletContext.getInitParameterNames();
}
/** {@inheritDoc} */
public String getParameter(String pName) {
return servletContext.getInitParameter(pName);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_1 |
crossvul-java_data_bad_5842_0 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.admin;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.projectforge.core.Configuration;
import org.projectforge.core.ConfigurationDO;
import org.projectforge.database.InitDatabaseDao;
import org.projectforge.user.UserDao;
import org.projectforge.web.wicket.AbstractForm;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.bootstrap.GridBuilder;
import org.projectforge.web.wicket.components.MaxLengthTextField;
import org.projectforge.web.wicket.components.RequiredMaxLengthTextField;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.components.TimeZonePanel;
import org.projectforge.web.wicket.flowlayout.DivPanel;
import org.projectforge.web.wicket.flowlayout.DivType;
import org.projectforge.web.wicket.flowlayout.FieldsetPanel;
import org.projectforge.web.wicket.flowlayout.InputPanel;
import org.projectforge.web.wicket.flowlayout.ParTextPanel;
import org.projectforge.web.wicket.flowlayout.PasswordPanel;
import org.projectforge.web.wicket.flowlayout.RadioGroupPanel;
public class SetupForm extends AbstractForm<SetupForm, SetupPage>
{
private static final long serialVersionUID = -277853572580468505L;
private static final String MAGIC_PASSWORD = "******";
@SpringBean(name = "userDao")
private UserDao userDao;
private final SetupTarget setupMode = SetupTarget.TEST_DATA;
private final TimeZone timeZone = TimeZone.getDefault();
private String sysopEMail;
private String feedbackEMail;
private String calendarDomain;
private final String adminUsername = InitDatabaseDao.DEFAULT_ADMIN_USER;
// @SuppressWarnings("unused")
// private String organization;
@SuppressWarnings("unused")
private String password;
@SuppressWarnings("unused")
private String passwordRepeat;
private String encryptedPassword;
public SetupForm(final SetupPage parentPage)
{
super(parentPage, "setupform");
}
@Override
@SuppressWarnings("serial")
protected void init()
{
add(createFeedbackPanel());
final GridBuilder gridBuilder = newGridBuilder(this, "flowform");
gridBuilder.newFormHeading(getString("administration.setup.heading"));
final DivPanel panel = gridBuilder.getPanel();
panel.add(new ParTextPanel(panel.newChildId(), getString("administration.setup.heading.subtitle")));
{
// RadioChoice mode
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.setup.target"));
final DivPanel radioPanel = new DivPanel(fs.newChildId(), DivType.RADIOBOX);
fs.add(radioPanel);
fs.setLabelFor(radioPanel);
final RadioGroupPanel<SetupTarget> radioGroup = new RadioGroupPanel<SetupTarget>(radioPanel.newChildId(), "setuptarget",
new PropertyModel<SetupTarget>(this, "setupMode"));
radioPanel.add(radioGroup);
for (final SetupTarget target : SetupTarget.values()) {
radioGroup.add(new Model<SetupTarget>(target), getString(target.getI18nKey()), getString(target.getI18nKey() + ".tooltip"));
}
}
// final RequiredMaxLengthTextField organizationField = new RequiredMaxLengthTextField(this, "organization", getString("organization"),
// new PropertyModel<String>(this, "organization"), 100);
// add(organizationField);
{
// User name
final FieldsetPanel fs = gridBuilder.newFieldset(getString("username"));
fs.add(new RequiredMaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "adminUsername"), 100));
}
final PasswordTextField passwordField = new PasswordTextField(PasswordPanel.WICKET_ID, new PropertyModel<String>(this, "password")) {
@Override
protected void onComponentTag(final ComponentTag tag)
{
super.onComponentTag(tag);
if (encryptedPassword == null) {
tag.put("value", "");
} else if (StringUtils.isEmpty(getConvertedInput()) == false) {
tag.put("value", MAGIC_PASSWORD);
}
}
};
{
// Password
final FieldsetPanel fs = gridBuilder.newFieldset(getString("password"));
passwordField.setRequired(true); // No setReset(true), otherwise uploading and re-entering passwords is a real pain.
fs.add(passwordField);
WicketUtils.setFocus(passwordField);
}
{
// Password repeat
final FieldsetPanel fs = gridBuilder.newFieldset(getString("passwordRepeat"));
final PasswordTextField passwordRepeatField = new PasswordTextField(PasswordPanel.WICKET_ID, new PropertyModel<String>(this,
"passwordRepeat")) {
@Override
protected void onComponentTag(final ComponentTag tag)
{
super.onComponentTag(tag);
if (encryptedPassword == null) {
tag.put("value", "");
} else if (StringUtils.isEmpty(getConvertedInput()) == false) {
tag.put("value", MAGIC_PASSWORD);
}
}
};
passwordRepeatField.setRequired(true); // No setReset(true), otherwise uploading and re-entering passwords is a real pain.
passwordRepeatField.add(new IValidator<String>() {
@Override
public void validate(final IValidatable<String> validatable)
{
final String input = validatable.getValue();
final String passwordInput = passwordField.getConvertedInput();
if (StringUtils.equals(input, passwordInput) == false) {
passwordRepeatField.error(getString("user.error.passwordAndRepeatDoesNotMatch"));
encryptedPassword = null;
return;
}
if (MAGIC_PASSWORD.equals(passwordInput) == false || encryptedPassword == null) {
final String errorMsgKey = userDao.checkPasswordQuality(passwordInput);
if (errorMsgKey != null) {
encryptedPassword = null;
passwordField.error(getString(errorMsgKey));
} else {
encryptedPassword = userDao.encryptPassword(passwordInput);
}
}
}
});
fs.add(passwordRepeatField);
}
{
// Time zone
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.timezone"));
final TimeZonePanel timeZone = new TimeZonePanel(fs.newChildId(), new PropertyModel<TimeZone>(this, "timeZone"));
fs.setLabelFor(timeZone);
fs.add(timeZone);
fs.addHelpIcon(getString("administration.configuration.param.timezone.description"));
}
{
// Calendar domain
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.calendarDomain"));
final RequiredMaxLengthTextField textField = new RequiredMaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this,
"calendarDomain"), ConfigurationDO.PARAM_LENGTH);
fs.add(textField);
textField.add(new IValidator<String>() {
@Override
public void validate(final IValidatable<String> validatable)
{
if (Configuration.isDomainValid(validatable.getValue()) == false) {
textField.error(getString("validation.error.generic"));
}
}
});
fs.addHelpIcon(getString("administration.configuration.param.calendarDomain.description"));
}
{
// E-Mail sysops
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.systemAdministratorEMail.label"),
getString("email"));
fs.add(new MaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "sysopEMail"), ConfigurationDO.PARAM_LENGTH));
fs.addHelpIcon(getString("administration.configuration.param.systemAdministratorEMail.description"));
}
{
// E-Mail sysops
final FieldsetPanel fs = gridBuilder.newFieldset(getString("administration.configuration.param.feedbackEMail.label"),
getString("email"));
fs.add(new MaxLengthTextField(InputPanel.WICKET_ID, new PropertyModel<String>(this, "feedbackEMail"), ConfigurationDO.PARAM_LENGTH));
fs.addHelpIcon(getString("administration.configuration.param.feedbackEMail.description"));
}
final RepeatingView actionButtons = new RepeatingView("buttons");
add(actionButtons);
{
final Button finishButton = new Button(SingleButtonPanel.WICKET_ID, new Model<String>("finish")) {
@Override
public final void onSubmit()
{
parentPage.finishSetup();
}
};
final SingleButtonPanel finishButtonPanel = new SingleButtonPanel(actionButtons.newChildId(), finishButton,
getString("administration.setup.finish"), SingleButtonPanel.DEFAULT_SUBMIT);
actionButtons.add(finishButtonPanel);
setDefaultButton(finishButton);
}
}
public SetupTarget getSetupMode()
{
return setupMode;
}
public TimeZone getTimeZone()
{
return timeZone;
}
/**
* @return the calendarDomain
*/
public String getCalendarDomain()
{
return calendarDomain;
}
public String getSysopEMail()
{
return sysopEMail;
}
public String getFeedbackEMail()
{
return feedbackEMail;
}
public String getEncryptedPassword()
{
return encryptedPassword;
}
public String getAdminUsername()
{
return adminUsername;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_5842_0 |
crossvul-java_data_bad_2031_6 | package org.jolokia.restrictor.policy;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.w3c.dom.*;
/**
* Check for location restrictions for CORS based cross browser platform requests
*
* @author roland
* @since 07.04.12
*/
public class CorsChecker extends AbstractChecker<String> {
private List<Pattern> patterns;
/**
* Constructor buiilding up this checker from the XML document provided.
* CORS sections look like
* <pre>
* <cors>
* <allow-origin>http://jolokia.org<allow-origin>
* <allow-origin>*://*.jmx4perl.org>
* </cors>
* </pre>
*
* @param pDoc the overall policy documents
*/
public CorsChecker(Document pDoc) {
NodeList corsNodes = pDoc.getElementsByTagName("cors");
if (corsNodes.getLength() > 0) {
patterns = new ArrayList<Pattern>();
for (int i = 0; i < corsNodes.getLength(); i++) {
Node corsNode = corsNodes.item(i);
NodeList nodes = corsNode.getChildNodes();
for (int j = 0;j <nodes.getLength();j++) {
Node node = nodes.item(j);
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
assertNodeName(node,"allow-origin");
String p = node.getTextContent().trim().toLowerCase();
p = Pattern.quote(p).replace("*","\\E.*\\Q");
patterns.add(Pattern.compile("^" + p + "$"));
}
}
}
}
/** {@inheritDoc} */
@Override
public boolean check(String pArg) {
if (patterns == null || patterns.size() == 0) {
return true;
}
for (Pattern pattern : patterns) {
if (pattern.matcher(pArg).matches()) {
return true;
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_6 |
crossvul-java_data_good_2028_4 | package io.hawt.web;
import io.hawt.system.ConfigManager;
import io.hawt.system.Helpers;
import org.jolokia.converter.Converters;
import org.jolokia.converter.json.JsonConvertOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Principal;
import java.util.*;
/**
*
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final transient Logger LOG = LoggerFactory.getLogger(LoginServlet.class);
protected Converters converters = new Converters();
protected JsonConvertOptions options = JsonConvertOptions.DEFAULT;
protected ConfigManager config;
private Integer timeout;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
config = (ConfigManager) servletConfig.getServletContext().getAttribute("ConfigManager");
if (config != null) {
String s = config.get("sessionTimeout", null);
if (s != null) {
try {
timeout = Integer.parseInt(s);
// timeout of 0 means default timeout
if (timeout == 0) {
timeout = null;
}
} catch (Exception e) {
// ignore and use default timeout value
}
}
}
LOG.info("hawtio login is using " + (timeout != null ? timeout + " sec." : "default") + " HttpSession timeout");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
final PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(false);
if (session != null) {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
LOG.warn("No security subject stored in existing session, invalidating");
session.invalidate();
Helpers.doForbidden(resp);
return;
}
sendResponse(session, subject, out);
return;
}
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(resp);
return;
}
Set<Principal> principals = subject.getPrincipals();
String username = null;
if (principals != null) {
for (Principal principal : principals) {
if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
username = principal.getName();
LOG.debug("Authorizing user {}", username);
}
}
}
session = req.getSession(true);
session.setAttribute("subject", subject);
session.setAttribute("user", username);
session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
if (timeout != null) {
session.setMaxInactiveInterval(timeout);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
}
sendResponse(session, subject, out);
}
protected void sendResponse(HttpSession session, Subject subject, PrintWriter out) {
Map<String, Object> answer = new HashMap<String, Object>();
List<Object> principals = new ArrayList<Object>();
for (Principal principal : subject.getPrincipals()) {
Map<String, String> data = new HashMap<String, String>();
data.put("type", principal.getClass().getName());
data.put("name", principal.getName());
principals.add(data);
}
List<Object> credentials = new ArrayList<Object>();
for (Object credential : subject.getPublicCredentials()) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", credential.getClass().getName());
data.put("credential", credential);
}
answer.put("principals", principals);
answer.put("credentials", credentials);
ServletHelpers.writeObject(converters, options, out, answer);
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2028_4 |
crossvul-java_data_bad_510_1 | /*
* Copyright 2016 http://www.hswebframework.org
*
* 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 org.hswebframework.web.authorization.oauth2.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2CodeAuthBeforeEvent;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.oauth2.client.OAuth2ServerConfigEntity;
import org.hswebframework.web.id.IDGenerator;
import org.hswebframework.web.oauth2.core.OAuth2Constants;
import org.hswebframework.web.service.oauth2.client.OAuth2ServerConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* @author zhouhao
*/
@Controller
@RequestMapping("${hsweb.web.mappings.oauth2-client-callback:oauth2}")
@Api(tags = "OAuth2.0-客户端-请求服务", value = "OAuth2.0客户端请求服务")
public class OAuth2ClientController {
private OAuth2RequestService oAuth2RequestService;
private OAuth2ServerConfigService oAuth2ServerConfigService;
@Autowired
public void setoAuth2ServerConfigService(OAuth2ServerConfigService oAuth2ServerConfigService) {
this.oAuth2ServerConfigService = oAuth2ServerConfigService;
}
@Autowired
public void setoAuth2RequestService(OAuth2RequestService oAuth2RequestService) {
this.oAuth2RequestService = oAuth2RequestService;
}
private static final String STATE_SESSION_KEY = "OAUTH2_STATE";
@GetMapping("/state")
@ResponseBody
@ApiOperation("申请一个state")
public ResponseMessage<String> requestState(HttpSession session) {
String state = IDGenerator.RANDOM.generate();
session.setAttribute(STATE_SESSION_KEY, state);
return ResponseMessage.ok(state);
}
@GetMapping("/boot/{serverId}")
@ApiOperation("跳转至OAuth2.0服务授权页面")
public RedirectView boot(@PathVariable String serverId,
@RequestParam(defaultValue = "/") String redirect,
HttpServletRequest request,
HttpSession session) throws UnsupportedEncodingException {
OAuth2ServerConfigEntity entity = oAuth2ServerConfigService.selectByPk(serverId);
if (entity == null) {
return new RedirectView("/401.html");
}
String callback = WebUtil.getBasePath(request)
.concat("oauth2/callback/")
.concat(serverId).concat("/?redirect=")
.concat(URLEncoder.encode(redirect, "UTF-8"));
RedirectView view = new RedirectView(entity.getRealUrl(entity.getAuthUrl()));
view.addStaticAttribute(OAuth2Constants.response_type, "code");
view.addStaticAttribute(OAuth2Constants.state, requestState(session).getResult());
view.addStaticAttribute(OAuth2Constants.client_id, entity.getClientId());
view.addStaticAttribute(OAuth2Constants.redirect_uri, callback);
return view;
}
@GetMapping("/callback/{serverId}")
@ApiOperation(value = "OAuth2.0授权完成后回调", hidden = true)
public RedirectView callback(@RequestParam(defaultValue = "/") String redirect,
@PathVariable String serverId,
@RequestParam String code,
@RequestParam String state,
HttpServletRequest request,
HttpSession session) throws UnsupportedEncodingException {
try {
String cachedState = (String) session.getAttribute(STATE_SESSION_KEY);
// if (!state.equals(cachedState)) throw new BusinessException("state error");
oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter));
return new RedirectView(URLDecoder.decode(redirect, "UTF-8"));
} finally {
session.removeAttribute(STATE_SESSION_KEY);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_510_1 |
crossvul-java_data_good_3058_1 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public synchronized List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public synchronized void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return viewGroupMixIn.getViews(); }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
final Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
}
});
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
setJDKs(req.bindJSONToList(JDK.class, json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
checkPermission(ADMINISTER);
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
checkPermission(ADMINISTER);
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_3058_1 |
crossvul-java_data_bad_2031_4 | package org.jolokia.restrictor;
import java.io.IOException;
import java.io.InputStream;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jolokia.restrictor.policy.*;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Restrictor, which is based on a policy file
*
* @author roland
* @since Jul 28, 2009
*/
public class PolicyRestrictor implements Restrictor {
// Checks HTTP method restrictions
private HttpMethodChecker httpChecker;
// Checks for certain request types
private RequestTypeChecker requestTypeChecker;
// Check for hosts and subnets
private NetworkChecker networkChecker;
// Check for CORS access
private CorsChecker corsChecker;
// Check for MBean access
private MBeanAccessChecker mbeanAccessChecker;
/**
* Construct a policy restrictor from an input stream
*
* @param pInput stream from where to fetch the policy data
*/
public PolicyRestrictor(InputStream pInput) {
Exception exp = null;
if (pInput == null) {
throw new SecurityException("No policy file given");
}
try {
Document doc =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pInput);
requestTypeChecker = new RequestTypeChecker(doc);
httpChecker = new HttpMethodChecker(doc);
networkChecker = new NetworkChecker(doc);
mbeanAccessChecker = new MBeanAccessChecker(doc);
corsChecker = new CorsChecker(doc);
}
catch (SAXException e) { exp = e; }
catch (IOException e) { exp = e; }
catch (ParserConfigurationException e) { exp = e; }
catch (MalformedObjectNameException e) { exp = e; }
if (exp != null) {
throw new SecurityException("Cannot parse policy file: " + exp,exp);
}
}
/** {@inheritDoc} */
public boolean isHttpMethodAllowed(HttpMethod method) {
return httpChecker.check(method);
}
/** {@inheritDoc} */
public boolean isTypeAllowed(RequestType pType) {
return requestTypeChecker.check(pType);
}
/** {@inheritDoc} */
public boolean isRemoteAccessAllowed(String ... pHostOrAddress) {
return networkChecker.check(pHostOrAddress);
}
/** {@inheritDoc} */
public boolean isCorsAccessAllowed(String pOrigin) {
return corsChecker.check(pOrigin);
}
/** {@inheritDoc} */
public boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
return check(RequestType.READ,pName,pAttribute);
}
/** {@inheritDoc} */
public boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
return check(RequestType.WRITE,pName, pAttribute);
}
/** {@inheritDoc} */
public boolean isOperationAllowed(ObjectName pName, String pOperation) {
return check(RequestType.EXEC,pName, pOperation);
}
/** {@inheritDoc} */
private boolean check(RequestType pType, ObjectName pName, String pValue) {
return mbeanAccessChecker.check(new MBeanAccessChecker.Arg(isTypeAllowed(pType), pType, pName, pValue));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_4 |
crossvul-java_data_good_2031_5 | package org.jolokia.restrictor;
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* A Restrictor is used to restrict the access to MBeans based on
* various parameters.
*
* @author roland
* @since Jul 28, 2009
*/
public interface Restrictor {
/**
* Check whether the HTTP method with which the request
* was sent is allowed.
*
* @param pMethod method to check
* @return true if there is no restriction on the method with which the request
* was sent, false otherwise
*/
boolean isHttpMethodAllowed(HttpMethod pMethod);
/**
* Check whether the provided command type is allowed in principal
*
* @param pType type to check
* @return true, if the type is allowed, false otherwise
*/
boolean isTypeAllowed(RequestType pType);
/**
* Check whether reading of an attribute is allowed
*
* @param pName MBean name
* @param pAttribute attribute to check
* @return true if access is allowed
*/
boolean isAttributeReadAllowed(ObjectName pName,String pAttribute);
/**
* Check whether writing of an attribute is allowed
*
* @param pName MBean name
* @param pAttribute attribute to check
* @return true if access is allowed
*/
boolean isAttributeWriteAllowed(ObjectName pName,String pAttribute);
/**
* Check whether execution of an operation is allowed
*
* @param pName MBean name
* @param pOperation attribute to check
* @return true if access is allowed
*/
boolean isOperationAllowed(ObjectName pName,String pOperation);
/**
* Check whether access from the connected client is allowed. If at least
* one of the given parameters matches, then this method returns true.
*
* @return true is access is allowed
* @param pHostOrAddress one or more host or address names
*/
boolean isRemoteAccessAllowed(String ... pHostOrAddress);
/**
* Check whether cross browser access via CORS is allowed. See the
* <a href="https://developer.mozilla.org/en/http_access_control">CORS</a> specification
* for details
*
* @param pOrigin the "Origin:" header provided within the request
* @param pIsStrictCheck whether doing a strict check
* @return true if this cross browser request allowed, false otherwise
*/
boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck);
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_5 |
crossvul-java_data_good_3058_2 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Failure;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.UnprotectedRootAction;
import hudson.model.User;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.util.HttpResponses;
import hudson.model.FreeStyleProject;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.OfflineCause;
import hudson.util.FormValidation;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.HttpResponse;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author kingfai
*
*/
public class JenkinsTest {
@Rule public JenkinsRule j = new JenkinsRule();
@Issue("SECURITY-406")
@Test
public void testUserCreationFromUrlForAdmins() throws Exception {
WebClient wc = j.createWebClient();
assertNull("User not supposed to exist", User.getById("nonexistent", false));
wc.assertFails("user/nonexistent", 404);
assertNull("User not supposed to exist", User.getById("nonexistent", false));
try {
User.ALLOW_USER_CREATION_VIA_URL = true;
// expected to work
wc.goTo("user/nonexistent2");
assertNotNull("User supposed to exist", User.getById("nonexistent2", false));
} finally {
User.ALLOW_USER_CREATION_VIA_URL = false;
}
}
@Test
public void testIsDisplayNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName("displayName");
Jenkins jenkins = Jenkins.getInstance();
assertTrue(jenkins.isDisplayNameUnique("displayName1", curJobName));
assertTrue(jenkins.isDisplayNameUnique(jobName, curJobName));
}
@Test
public void testIsDisplayNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
assertFalse(jenkins.isDisplayNameUnique(displayName, curJobName));
}
@Test
public void testIsDisplayNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String displayName = "currentProjectDisplayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
// should be true as we don't test against the current job
assertTrue(jenkins.isDisplayNameUnique(displayName, curJobName));
}
@Test
public void testIsNameUniqueTrue() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
assertTrue(jenkins.isNameUnique("jobName1", curJobName));
}
@Test
public void testIsNameUniqueFalse() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
assertFalse(jenkins.isNameUnique(jobName, curJobName));
}
@Test
public void testIsNameUniqueSameAsCurrentJob() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
j.createFreeStyleProject(curJobName);
j.createFreeStyleProject(jobName);
Jenkins jenkins = Jenkins.getInstance();
// true because we don't test against the current job
assertTrue(jenkins.isNameUnique(curJobName, curJobName));
}
@Test
public void testDoCheckDisplayNameUnique() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName("displayName");
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName("1displayName", curJobName);
assertEquals(FormValidation.ok(), v);
}
@Test
public void testDoCheckDisplayNameSameAsDisplayName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName(displayName, curJobName);
assertEquals(FormValidation.Kind.WARNING, v.kind);
}
@Test
public void testDoCheckDisplayNameSameAsJobName() throws Exception {
final String curJobName = "curJobName";
final String jobName = "jobName";
final String displayName = "displayName";
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
curProject.setDisplayName("currentProjectDisplayName");
FreeStyleProject p = j.createFreeStyleProject(jobName);
p.setDisplayName(displayName);
Jenkins jenkins = Jenkins.getInstance();
FormValidation v = jenkins.doCheckDisplayName(jobName, curJobName);
assertEquals(FormValidation.Kind.WARNING, v.kind);
}
@Test
public void testDoCheckViewName_GoodName() throws Exception {
String[] viewNames = new String[] {
"", "Jenkins"
};
Jenkins jenkins = Jenkins.getInstance();
for (String viewName : viewNames) {
FormValidation v = jenkins.doCheckViewName(viewName);
assertEquals(FormValidation.Kind.OK, v.kind);
}
}
@Test
public void testDoCheckViewName_NotGoodName() throws Exception {
String[] viewNames = new String[] {
"Jenkins?", "Jenkins*", "Jenkin/s", "Jenkin\\s", "jenkins%",
"Jenkins!", "Jenkins[]", "Jenkin<>s", "^Jenkins", ".."
};
Jenkins jenkins = Jenkins.getInstance();
for (String viewName : viewNames) {
FormValidation v = jenkins.doCheckViewName(viewName);
assertEquals(FormValidation.Kind.ERROR, v.kind);
}
}
@Test @Issue("JENKINS-12251")
public void testItemFullNameExpansion() throws Exception {
HtmlForm f = j.createWebClient().goTo("configure").getFormByName("config");
f.getInputByName("_.rawBuildsDir").setValueAttribute("${JENKINS_HOME}/test12251_builds/${ITEM_FULL_NAME}");
f.getInputByName("_.rawWorkspaceDir").setValueAttribute("${JENKINS_HOME}/test12251_ws/${ITEM_FULL_NAME}");
j.submit(f);
// build a dummy project
MavenModuleSet m = j.createMavenProject();
m.setScm(new ExtractResourceSCM(getClass().getResource("/simple-projects.zip")));
MavenModuleSetBuild b = m.scheduleBuild2(0).get();
// make sure these changes are effective
assertTrue(b.getWorkspace().getRemote().contains("test12251_ws"));
assertTrue(b.getRootDir().toString().contains("test12251_builds"));
}
/**
* Makes sure access to "/foobar" for UnprotectedRootAction gets through.
*/
@Test @Issue("JENKINS-14113")
public void testUnprotectedRootAction() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
WebClient wc = j.createWebClient();
wc.goTo("foobar");
wc.goTo("foobar/");
wc.goTo("foobar/zot");
// and make sure this fails
wc.assertFails("foobar-zot/", HttpURLConnection.HTTP_INTERNAL_ERROR);
assertEquals(3,j.jenkins.getExtensionList(RootAction.class).get(RootActionImpl.class).count);
}
@Test
public void testDoScript() throws Exception {
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
@Override public boolean hasPermission(String sid, Permission p) {
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
}
};
gmas.add(Jenkins.ADMINISTER, "alice");
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
gmas.add(Jenkins.READ, "bob");
gmas.add(Jenkins.ADMINISTER, "charlie");
j.jenkins.setAuthorizationStrategy(gmas);
WebClient wc = j.createWebClient();
wc.login("alice");
wc.goTo("script");
wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD);
assertNull(System.getProperty("hack"));
WebRequest req = new WebRequest(new URL(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST);
wc.getPage(wc.addCrumb(req));
assertEquals("me", System.getProperty("hack"));
wc.assertFails("scriptText?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD);
req = new WebRequest(new URL(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST);
wc.getPage(wc.addCrumb(req));
assertEquals("you", System.getProperty("huck"));
wc.login("bob");
wc.assertFails("script", HttpURLConnection.HTTP_FORBIDDEN);
wc.login("charlie");
wc.assertFails("script", HttpURLConnection.HTTP_FORBIDDEN);
}
@Test
public void testDoEval() throws Exception {
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
@Override public boolean hasPermission(String sid, Permission p) {
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
}
};
gmas.add(Jenkins.ADMINISTER, "alice");
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
gmas.add(Jenkins.READ, "bob");
gmas.add(Jenkins.ADMINISTER, "charlie");
j.jenkins.setAuthorizationStrategy(gmas);
WebClient wc = j.createWebClient();
wc.login("alice");
wc.assertFails("eval", HttpURLConnection.HTTP_BAD_METHOD);
assertEquals("3", eval(wc));
wc.login("bob");
try {
eval(wc);
fail("bob has only READ");
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
wc.login("charlie");
try {
eval(wc);
fail("charlie has ADMINISTER but not RUN_SCRIPTS");
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
}
private String eval(WebClient wc) throws Exception {
WebRequest req = new WebRequest(wc.createCrumbedUrl("eval"), HttpMethod.POST);
req.setEncodingType(null);
req.setRequestBody("<j:jelly xmlns:j='jelly:core'>${1+2}</j:jelly>");
return wc.getPage(req).getWebResponse().getContentAsString();
}
@TestExtension("testUnprotectedRootAction")
public static class RootActionImpl implements UnprotectedRootAction {
private int count;
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "foobar";
}
public HttpResponse doDynamic() {
assertTrue(Jenkins.getInstance().getAuthentication().getName().equals("anonymous"));
count++;
return HttpResponses.html("OK");
}
}
@TestExtension("testUnprotectedRootAction")
public static class ProtectedRootActionImpl implements RootAction {
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "foobar-zot";
}
public HttpResponse doDynamic() {
throw new AssertionError();
}
}
@Test @Issue("JENKINS-20866")
public void testErrorPageShouldBeAnonymousAccessible() throws Exception {
HudsonPrivateSecurityRealm s = new HudsonPrivateSecurityRealm(false, false, null);
User alice = s.createAccount("alice", "alice");
j.jenkins.setSecurityRealm(s);
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
// no anonymous read access
assertTrue(!Jenkins.getInstance().getACL().hasPermission(Jenkins.ANONYMOUS,Jenkins.READ));
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("error/reportError");
assertEquals(p.asText(), 400, p.getWebResponse().getStatusCode()); // not 403 forbidden
assertTrue(p.getWebResponse().getContentAsString().contains("My car is black"));
}
@TestExtension("testErrorPageShouldBeAnonymousAccessible")
public static class ReportError implements UnprotectedRootAction {
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "error";
}
public HttpResponse doReportError() {
return new Failure("My car is black");
}
}
@Test @Issue("JENKINS-23551")
public void testComputerListenerNotifiedOnRestart() {
// Simulate restart calling listeners
for (RestartListener listener : RestartListener.all())
listener.onRestart();
ArgumentCaptor<OfflineCause> captor = ArgumentCaptor.forClass(OfflineCause.class);
Mockito.verify(listenerMock).onOffline(Mockito.eq(j.jenkins.toComputer()), captor.capture());
assertTrue(captor.getValue().toString().contains("restart"));
}
@TestExtension(value = "testComputerListenerNotifiedOnRestart")
public static final ComputerListener listenerMock = Mockito.mock(ComputerListener.class);
@Test
public void runScriptOnOfflineComputer() throws Exception {
DumbSlave slave = j.createSlave(true);
j.disconnectSlave(slave);
URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)");
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
WebRequest req = new WebRequest(url, HttpMethod.POST);
Page page = wc.getPage(wc.addCrumb(req));
WebResponse rsp = page.getWebResponse();
assertThat(rsp.getContentAsString(), containsString("Node is offline"));
assertThat(rsp.getStatusCode(), equalTo(404));
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_3058_2 |
crossvul-java_data_good_2028_5 | package io.hawt.web;
import org.apache.commons.codec.binary.Base64;
import javax.security.auth.Subject;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
/**
* @author Stan Lewis
*/
public class LoginTokenServlet extends LoginServlet {
private static final long serialVersionUID = 1L;
public static final String LOGIN_TOKEN = "LoginToken";
@Override
protected void sendResponse(HttpSession session, Subject subject, PrintWriter out) {
String token = (String) session.getAttribute(LOGIN_TOKEN);
if ( token == null) {
byte[] seed = (subject.toString() + new Long(System.currentTimeMillis()).toString()).getBytes();
SecureRandom random = new SecureRandom(seed);
byte[] tokenBytes = new byte[128];
random.nextBytes(tokenBytes);
token = Base64.encodeBase64String(tokenBytes);
session.setAttribute(LOGIN_TOKEN, token);
}
Map<String, String> answer = new HashMap<String, String>();
answer.put("token", token);
ServletHelpers.writeObject(converters, options, out, answer);
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2028_5 |
crossvul-java_data_bad_2031_0 | package org.jolokia.backend;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.management.*;
import org.jolokia.backend.executor.NotChangedException;
import org.jolokia.config.ConfigKey;
import org.jolokia.config.Configuration;
import org.jolokia.converter.Converters;
import org.jolokia.converter.json.JsonConvertOptions;
import org.jolokia.detector.ServerHandle;
import org.jolokia.discovery.AgentDetails;
import org.jolokia.discovery.AgentDetailsHolder;
import org.jolokia.history.HistoryStore;
import org.jolokia.request.JmxRequest;
import org.jolokia.restrictor.AllowAllRestrictor;
import org.jolokia.restrictor.Restrictor;
import org.jolokia.util.*;
import org.json.simple.JSONObject;
import static org.jolokia.config.ConfigKey.*;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Backendmanager for dispatching to various backends based on a given
* {@link JmxRequest}
*
* @author roland
* @since Nov 11, 2009
*/
public class BackendManager implements AgentDetailsHolder {
// Dispatches request to local MBeanServer
private LocalRequestDispatcher localDispatcher;
// Converter for converting various attribute object types
// a JSON representation
private Converters converters;
// Hard limits for conversion
private JsonConvertOptions.Builder convertOptionsBuilder;
// Handling access restrictions
private Restrictor restrictor;
// History handler
private HistoryStore historyStore;
// Storage for storing debug information
private DebugStore debugStore;
// Loghandler for dispatching logs
private LogHandler logHandler;
// List of RequestDispatchers to consult
private List<RequestDispatcher> requestDispatchers;
// Initialize used for late initialization
// ("volatile: because we use double-checked locking later on
// --> http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)
private volatile Initializer initializer;
// Details about the agent inclding the server handle
private AgentDetails agentDetails;
/**
* Construct a new backend manager with the given configuration and which allows
* every operation (no restrictor)
*
* @param pConfig configuration used for tuning this handler's behaviour
* @param pLogHandler logger
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler) {
this(pConfig, pLogHandler, null);
}
/**
* Construct a new backend manager with the given configuration.
*
* @param pConfig configuration used for tuning this handler's behaviour
* @param pLogHandler logger
* @param pRestrictor a restrictor for limiting access. Can be null in which case every operation is allowed
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler, Restrictor pRestrictor) {
this(pConfig,pLogHandler,pRestrictor,false);
}
/**
* Construct a new backend manager with the given configuration.
*
* @param pConfig configuration map used for tuning this handler's behaviour
* @param pLogHandler logger
* @param pRestrictor a restrictor for limiting access. Can be null in which case every operation is allowed
* @param pLazy whether the initialisation should be done lazy
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler, Restrictor pRestrictor, boolean pLazy) {
// Access restrictor
restrictor = pRestrictor != null ? pRestrictor : new AllowAllRestrictor();
// Log handler for putting out debug
logHandler = pLogHandler;
// Details about the agent, used for discovery
agentDetails = new AgentDetails(pConfig);
if (pLazy) {
initializer = new Initializer(pConfig);
} else {
init(pConfig);
initializer = null;
}
}
/**
* Handle a single JMXRequest. The response status is set to 200 if the request
* was successful
*
* @param pJmxReq request to perform
* @return the already converted answer.
* @throws InstanceNotFoundException
* @throws AttributeNotFoundException
* @throws ReflectionException
* @throws MBeanException
*/
public JSONObject handleRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException,
ReflectionException, MBeanException, IOException {
lazyInitIfNeeded();
boolean debug = isDebug();
long time = 0;
if (debug) {
time = System.currentTimeMillis();
}
JSONObject json;
try {
json = callRequestDispatcher(pJmxReq);
// Update global history store, add timestamp and possibly history information to the request
historyStore.updateAndAdd(pJmxReq,json);
json.put("status",200 /* success */);
} catch (NotChangedException exp) {
// A handled indicates that its value hasn't changed. We return an status with
//"304 Not Modified" similar to the HTTP status code (http://en.wikipedia.org/wiki/HTTP_status)
json = new JSONObject();
json.put("request",pJmxReq.toJSON());
json.put("status",304);
json.put("timestamp",System.currentTimeMillis() / 1000);
}
if (debug) {
debug("Execution time: " + (System.currentTimeMillis() - time) + " ms");
debug("Response: " + json);
}
return json;
}
/**
* Convert a Throwable to a JSON object so that it can be included in an error response
*
* @param pExp throwable to convert
* @param pJmxReq the request from where to take the serialization options
* @return the exception.
*/
public Object convertExceptionToJson(Throwable pExp, JmxRequest pJmxReq) {
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
try {
JSONObject expObj =
(JSONObject) converters.getToJsonConverter().convertToJson(pExp,null,opts);
return expObj;
} catch (AttributeNotFoundException e) {
// Cannot happen, since we dont use a path
return null;
}
}
/**
* Remove MBeans
*/
public void destroy() {
try {
localDispatcher.destroy();
} catch (JMException e) {
error("Cannot unregister MBean: " + e,e);
}
}
/**
* Check whether remote access from the given client is allowed.
*
* @param pRemoteHost remote host to check against
* @param pRemoteAddr alternative IP address
* @return true if remote access is allowed
*/
public boolean isRemoteAccessAllowed(String pRemoteHost, String pRemoteAddr) {
return restrictor.isRemoteAccessAllowed(pRemoteHost, pRemoteAddr);
}
/**
* Check whether CORS access is allowed for the given origin.
*
* @param pOrigin origin URL which needs to be checked
* @return true if icors access is allowed
*/
public boolean isCorsAccessAllowed(String pOrigin) {
return restrictor.isCorsAccessAllowed(pOrigin);
}
/**
* Log at info level
*
* @param msg to log
*/
public void info(String msg) {
logHandler.info(msg);
if (debugStore != null) {
debugStore.log(msg);
}
}
/**
* Log at debug level
*
* @param msg message to log
*/
public void debug(String msg) {
logHandler.debug(msg);
if (debugStore != null) {
debugStore.log(msg);
}
}
/**
* Log at error level.
*
* @param message message to log
* @param t ecxeption occured
*/
public void error(String message, Throwable t) {
// Must not be final so that we can mock it in EasyMock for our tests
logHandler.error(message, t);
if (debugStore != null) {
debugStore.log(message, t);
}
}
/**
* Whether debug is switched on
*
* @return true if debug is switched on
*/
public boolean isDebug() {
return debugStore != null && debugStore.isDebug();
}
/**
* Get the details for the agent which can be updated or used
*
* @return agent details
*/
public AgentDetails getAgentDetails() {
return agentDetails;
}
// ==========================================================================================================
// Initialized used for late initialisation as it is required for the agent when used
// as startup options
private final class Initializer {
private Configuration config;
private Initializer(Configuration pConfig) {
config = pConfig;
}
void init() {
BackendManager.this.init(config);
}
}
// Run initialized if not already done
private void lazyInitIfNeeded() {
if (initializer != null) {
synchronized (this) {
if (initializer != null) {
initializer.init();
initializer = null;
}
}
}
}
// Initialize this object;
private void init(Configuration pConfig) {
// Central objects
converters = new Converters();
initLimits(pConfig);
// Create and remember request dispatchers
localDispatcher = new LocalRequestDispatcher(converters,
restrictor,
pConfig,
logHandler);
ServerHandle serverHandle = localDispatcher.getServerHandle();
requestDispatchers = createRequestDispatchers(pConfig.get(DISPATCHER_CLASSES),
converters,serverHandle,restrictor);
requestDispatchers.add(localDispatcher);
// Backendstore for remembering agent state
initMBeans(pConfig);
agentDetails.setServerInfo(serverHandle.getVendor(),serverHandle.getProduct(),serverHandle.getVersion());
}
private void initLimits(Configuration pConfig) {
// Max traversal depth
if (pConfig != null) {
convertOptionsBuilder = new JsonConvertOptions.Builder(
getNullSaveIntLimit(pConfig.get(MAX_DEPTH)),
getNullSaveIntLimit(pConfig.get(MAX_COLLECTION_SIZE)),
getNullSaveIntLimit(pConfig.get(MAX_OBJECTS))
);
} else {
convertOptionsBuilder = new JsonConvertOptions.Builder();
}
}
private int getNullSaveIntLimit(String pValue) {
return pValue != null ? Integer.parseInt(pValue) : 0;
}
// Construct configured dispatchers by reflection. Returns always
// a list, an empty one if no request dispatcher should be created
private List<RequestDispatcher> createRequestDispatchers(String pClasses,
Converters pConverters,
ServerHandle pServerHandle,
Restrictor pRestrictor) {
List<RequestDispatcher> ret = new ArrayList<RequestDispatcher>();
if (pClasses != null && pClasses.length() > 0) {
String[] names = pClasses.split("\\s*,\\s*");
for (String name : names) {
ret.add(createDispatcher(name, pConverters, pServerHandle, pRestrictor));
}
}
return ret;
}
// Create a single dispatcher
private RequestDispatcher createDispatcher(String pDispatcherClass,
Converters pConverters,
ServerHandle pServerHandle, Restrictor pRestrictor) {
try {
Class clazz = this.getClass().getClassLoader().loadClass(pDispatcherClass);
Constructor constructor = clazz.getConstructor(Converters.class,
ServerHandle.class,
Restrictor.class);
return (RequestDispatcher)
constructor.newInstance(pConverters,
pServerHandle,
pRestrictor);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Couldn't load class " + pDispatcherClass + ": " + e,e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + pDispatcherClass + " has invalid constructor: " + e,e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Constructor of " + pDispatcherClass + " couldn't be accessed: " + e,e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(pDispatcherClass + " couldn't be instantiated: " + e,e);
}
}
// call the an appropriate request dispatcher
private JSONObject callRequestDispatcher(JmxRequest pJmxReq)
throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
Object retValue = null;
boolean useValueWithPath = false;
boolean found = false;
for (RequestDispatcher dispatcher : requestDispatchers) {
if (dispatcher.canHandle(pJmxReq)) {
retValue = dispatcher.dispatchRequest(pJmxReq);
useValueWithPath = dispatcher.useReturnValueWithPath(pJmxReq);
found = true;
break;
}
}
if (!found) {
throw new IllegalStateException("Internal error: No dispatcher found for handling " + pJmxReq);
}
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
Object jsonResult =
converters.getToJsonConverter()
.convertToJson(retValue, useValueWithPath ? pJmxReq.getPathParts() : null, opts);
JSONObject jsonObject = new JSONObject();
jsonObject.put("value",jsonResult);
jsonObject.put("request",pJmxReq.toJSON());
return jsonObject;
}
private JsonConvertOptions getJsonConvertOptions(JmxRequest pJmxReq) {
return convertOptionsBuilder.
maxDepth(pJmxReq.getParameterAsInt(ConfigKey.MAX_DEPTH)).
maxCollectionSize(pJmxReq.getParameterAsInt(ConfigKey.MAX_COLLECTION_SIZE)).
maxObjects(pJmxReq.getParameterAsInt(ConfigKey.MAX_OBJECTS)).
faultHandler(pJmxReq.getValueFaultHandler()).
build();
}
// init various application wide stores for handling history and debug output.
private void initMBeans(Configuration pConfig) {
int maxEntries = pConfig.getAsInt(HISTORY_MAX_ENTRIES);
int maxDebugEntries = pConfig.getAsInt(DEBUG_MAX_ENTRIES);
historyStore = new HistoryStore(maxEntries);
debugStore = new DebugStore(maxDebugEntries, pConfig.getAsBoolean(DEBUG));
try {
localDispatcher.initMBeans(historyStore, debugStore);
} catch (NotCompliantMBeanException e) {
intError("Error registering config MBean: " + e, e);
} catch (MBeanRegistrationException e) {
intError("Cannot register MBean: " + e, e);
} catch (MalformedObjectNameException e) {
intError("Invalid name for config MBean: " + e, e);
}
}
// Final private error log for use in the constructor above
private void intError(String message,Throwable t) {
logHandler.error(message, t);
debugStore.log(message, t);
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_0 |
crossvul-java_data_good_2031_7 | package org.jolokia.backend;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.IOException;
import java.util.Map;
import javax.management.*;
import org.jolokia.backend.executor.NotChangedException;
import org.jolokia.config.ConfigKey;
import org.jolokia.config.Configuration;
import org.jolokia.converter.Converters;
import org.jolokia.detector.ServerHandle;
import org.jolokia.request.JmxRequest;
import org.jolokia.request.JmxRequestBuilder;
import org.jolokia.restrictor.Restrictor;
import org.jolokia.util.*;
import org.json.simple.JSONObject;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author roland
* @since Jun 15, 2010
*/
public class BackendManagerTest {
Configuration config;
private LogHandler log = new LogHandler.StdoutLogHandler(true);
@BeforeTest
public void setup() {
config = new Configuration(ConfigKey.AGENT_ID,"test");
}
@Test
public void simpleRead() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DEBUG,"true",ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory")
.attribute("HeapMemoryUsage")
.build();
JSONObject ret = backendManager.handleRequest(req);
assertTrue((Long) ((Map) ret.get("value")).get("used") > 0);
backendManager.destroy();
}
@Test
public void notChanged() throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.LIST).build();
JSONObject ret = backendManager.handleRequest(req);
assertEquals(ret.get("status"),304);
backendManager.destroy();
}
@Test
public void lazyInit() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
BackendManager backendManager = new BackendManager(config, log, null, true /* Lazy Init */ );
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory")
.attribute("HeapMemoryUsage")
.build();
JSONObject ret = backendManager.handleRequest(req);
assertTrue((Long) ((Map) ret.get("value")).get("used") > 0);
backendManager.destroy();
}
@Test
public void requestDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config, log);
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
backendManager.handleRequest(req);
assertTrue(RequestDispatcherTest.called);
backendManager.destroy();
}
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*invalid constructor.*")
public void requestDispatcherWithWrongDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherWrong.class.getName(),ConfigKey.AGENT_ID,"test");
new BackendManager(config,log);
}
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*blub.bla.Dispatcher.*")
public void requestDispatcherWithUnkownDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException {
Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,"blub.bla.Dispatcher",ConfigKey.AGENT_ID,"test");
new BackendManager(config,log);
}
@Test
public void debugging() {
RecordingLogHandler lhandler = new RecordingLogHandler();
BackendManager backendManager = new BackendManager(config,lhandler);
lhandler.error = 0;
lhandler.debug = 0;
lhandler.info = 0;
backendManager.debug("test");
assertEquals(lhandler.debug,1);
backendManager.error("test",new Exception());
assertEquals(lhandler.error,1);
backendManager.info("test");
assertEquals(lhandler.info,1);
backendManager.destroy();
}
@Test
public void defaultConfig() {
Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test");
BackendManager backendManager = new BackendManager(config,log);
backendManager.destroy();
}
@Test
public void doubleInit() {
BackendManager b1 = new BackendManager(config,log);
BackendManager b2 = new BackendManager(config,log);
b2.destroy();
b1.destroy();
}
@Test
public void remoteAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1"));
backendManager.destroy();
}
@Test
public void corsAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isOriginAllowed("http://bla.com",false));
backendManager.destroy();
}
@Test
public void convertError() throws MalformedObjectNameException {
BackendManager backendManager = new BackendManager(config,log);
Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb"));
JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build();
JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);
assertTrue(!jsonError.containsKey("stackTrace"));
assertEquals(jsonError.get("message"),"Hans");
assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb");
backendManager.destroy();
}
// =========================================================================================
static class RequestDispatcherTest implements RequestDispatcher {
static boolean called = false;
public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {
assertNotNull(pConverters);
assertNotNull(pRestrictor);
}
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
called = true;
if (pJmxReq.getType() == RequestType.READ) {
return new JSONObject();
} else if (pJmxReq.getType() == RequestType.WRITE) {
return "faultyFormat";
} else if (pJmxReq.getType() == RequestType.LIST) {
throw new NotChangedException(pJmxReq);
}
return null;
}
public boolean canHandle(JmxRequest pJmxRequest) {
return true;
}
public boolean useReturnValueWithPath(JmxRequest pJmxRequest) {
return false;
}
}
// ========================================================
static class RequestDispatcherWrong implements RequestDispatcher {
// No special constructor --> fail
public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException {
return null;
}
public boolean canHandle(JmxRequest pJmxRequest) {
return false;
}
public boolean useReturnValueWithPath(JmxRequest pJmxRequest) {
return false;
}
}
private class RecordingLogHandler implements LogHandler {
int debug = 0;
int info = 0;
int error = 0;
public void debug(String message) {
debug++;
}
public void info(String message) {
info++;
}
public void error(String message, Throwable t) {
error++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_7 |
crossvul-java_data_good_4646_2 | package com.softwaremill.session.javadsl;
import akka.http.javadsl.model.FormData;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.headers.Cookie;
import akka.http.javadsl.model.headers.HttpCookie;
import akka.http.javadsl.model.headers.RawHeader;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.japi.Pair;
import com.softwaremill.session.CsrfCheckMode;
import com.softwaremill.session.SessionContinuity;
import com.softwaremill.session.SetSessionTransport;
import org.junit.Assert;
import org.junit.Test;
public class CsrfDirectivesTest extends HttpSessionAwareDirectivesTest {
protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> csrfCheckMode) {
return route(
testDirectives.randomTokenCsrfProtection(csrfCheckMode, () ->
route(
get(() ->
path("site", () ->
complete("ok")
)
),
post(() ->
route(
path("login", () ->
testDirectives.setNewCsrfToken(csrfCheckMode, () ->
complete("ok"))),
path("transfer_money", () ->
complete("ok")
)
)
)
)
)
);
}
@Test
public void shouldSetTheCsrfCookieOnTheFirstGetRequestOnly() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpResponse response = testRouteResult.response();
HttpCookie csrfCookie = getCsrfTokenCookieValues(response);
Assert.assertNotNull(csrfCookie.value());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.GET("/site")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpResponse response2 = testRouteResult2.response();
HttpCookie cookieValues2 = getCsrfTokenCookieValues(response2);
Assert.assertNull(cookieValues2);
}
@Test
public void shouldRejectRequestsIfTheCsrfCookieDoesNotMatchTheHeaderValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, "something else"))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.FORBIDDEN);
}
@Test
public void shouldRejectRequestsIfTheCsrfCookieIsNotSet() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money"));
// then
testRouteResult2
.assertStatusCode(StatusCodes.FORBIDDEN);
}
@Test
public void shouldRejectRequestsIfTheCsrfCookieAndTheHeaderAreEmpty() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money")
.addHeader(Cookie.create(csrfCookieName, ""))
.addHeader(RawHeader.create(csrfSubmittedName, ""))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.FORBIDDEN);
}
@Test
public void shouldAcceptRequestsIfTheCsrfCookieMatchesTheHeaderValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
}
@Test
public void shouldAcceptRequestsIfTheCsrfCookieMatchesTheFormFieldValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderAndFormMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
final FormData formData = FormData.create(
Pair.create(csrfSubmittedName, csrfCookie.value())
);
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money").withEntity(formData.toEntity())
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
}
@Test
public void shouldSetANewCsrfCookieWhenRequested() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/login")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpCookie csrfCookie2 = getCsrfTokenCookieValues(testRouteResult2.response());
Assert.assertNotEquals(csrfCookie.value(), csrfCookie2.value());
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_4646_2 |
crossvul-java_data_bad_4646_2 | package com.softwaremill.session.javadsl;
import akka.http.javadsl.model.FormData;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.headers.Cookie;
import akka.http.javadsl.model.headers.HttpCookie;
import akka.http.javadsl.model.headers.RawHeader;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.japi.Pair;
import com.softwaremill.session.CsrfCheckMode;
import com.softwaremill.session.SessionContinuity;
import com.softwaremill.session.SetSessionTransport;
import org.junit.Assert;
import org.junit.Test;
public class CsrfDirectivesTest extends HttpSessionAwareDirectivesTest {
protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> csrfCheckMode) {
return route(
testDirectives.randomTokenCsrfProtection(csrfCheckMode, () ->
route(
get(() ->
path("site", () ->
complete("ok")
)
),
post(() ->
route(
path("login", () ->
testDirectives.setNewCsrfToken(csrfCheckMode, () ->
complete("ok"))),
path("transfer_money", () ->
complete("ok")
)
)
)
)
)
);
}
@Test
public void shouldSetTheCsrfCookieOnTheFirstGetRequestOnly() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpResponse response = testRouteResult.response();
HttpCookie csrfCookie = getCsrfTokenCookieValues(response);
Assert.assertNotNull(csrfCookie.value());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.GET("/site")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpResponse response2 = testRouteResult2.response();
HttpCookie cookieValues2 = getCsrfTokenCookieValues(response2);
Assert.assertNull(cookieValues2);
}
@Test
public void shouldRejectRequestsIfTheCsrfCookieDoesNotMatchTheHeaderValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, "something else"))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.FORBIDDEN);
}
@Test
public void shouldRejectRequestsIfTheCsrfCookieIsNotSet() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money"));
// then
testRouteResult2
.assertStatusCode(StatusCodes.FORBIDDEN);
}
@Test
public void shouldAcceptRequestsIfTheCsrfCookieMatchesTheHeaderValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
}
@Test
public void shouldAcceptRequestsIfTheCsrfCookieMatchesTheFormFieldValue() {
// given
final Route route = createCsrfRouteWithCheckHeaderAndFormMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
final FormData formData = FormData.create(
Pair.create(csrfSubmittedName, csrfCookie.value())
);
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/transfer_money").withEntity(formData.toEntity())
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
}
@Test
public void shouldSetANewCsrfCookieWhenRequested() {
// given
final Route route = createCsrfRouteWithCheckHeaderMode();
// when
TestRouteResult testRouteResult = testRoute(route)
.run(HttpRequest.GET("/site"));
// then
testRouteResult
.assertStatusCode(StatusCodes.OK);
// and
HttpCookie csrfCookie = getCsrfTokenCookieValues(testRouteResult.response());
/* second request */
// when
TestRouteResult testRouteResult2 = testRoute(route)
.run(HttpRequest.POST("/login")
.addHeader(Cookie.create(csrfCookieName, csrfCookie.value()))
.addHeader(RawHeader.create(csrfSubmittedName, csrfCookie.value()))
);
// then
testRouteResult2
.assertStatusCode(StatusCodes.OK)
.assertEntity("ok");
// and
HttpCookie csrfCookie2 = getCsrfTokenCookieValues(testRouteResult2.response());
Assert.assertNotEquals(csrfCookie.value(), csrfCookie2.value());
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_4646_2 |
crossvul-java_data_bad_2031_3 | package org.jolokia.restrictor;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import javax.management.ObjectName;
import org.jolokia.util.HttpMethod;
import org.jolokia.util.RequestType;
/**
* Base restrictor which alway returns the constant given
* at construction time
*
* @author roland
* @since 06.10.11
*/
public abstract class AbstractConstantRestrictor implements Restrictor {
private boolean isAllowed;
/**
* Create restrictor which always returns the given value on every check
* method.
*
* @param pAllowed whether access is allowed or denied
*/
protected AbstractConstantRestrictor(boolean pAllowed) {
isAllowed = pAllowed;
}
/** {@inheritDoc} */
public final boolean isHttpMethodAllowed(HttpMethod pMethod) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isTypeAllowed(RequestType pType) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isOperationAllowed(ObjectName pName, String pOperation) {
return isAllowed;
}
/** {@inheritDoc} */
public final boolean isRemoteAccessAllowed(String... pHostOrAddress) {
return isAllowed;
}
/** {@inheritDoc} */
public boolean isCorsAccessAllowed(String pOrigin) {
return isAllowed;
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/bad_2031_3 |
crossvul-java_data_good_2031_0 | package org.jolokia.backend;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.management.*;
import org.jolokia.backend.executor.NotChangedException;
import org.jolokia.config.ConfigKey;
import org.jolokia.config.Configuration;
import org.jolokia.converter.Converters;
import org.jolokia.converter.json.JsonConvertOptions;
import org.jolokia.detector.ServerHandle;
import org.jolokia.discovery.AgentDetails;
import org.jolokia.discovery.AgentDetailsHolder;
import org.jolokia.history.HistoryStore;
import org.jolokia.request.JmxRequest;
import org.jolokia.restrictor.AllowAllRestrictor;
import org.jolokia.restrictor.Restrictor;
import org.jolokia.util.*;
import org.json.simple.JSONObject;
import static org.jolokia.config.ConfigKey.*;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
/**
* Backendmanager for dispatching to various backends based on a given
* {@link JmxRequest}
*
* @author roland
* @since Nov 11, 2009
*/
public class BackendManager implements AgentDetailsHolder {
// Dispatches request to local MBeanServer
private LocalRequestDispatcher localDispatcher;
// Converter for converting various attribute object types
// a JSON representation
private Converters converters;
// Hard limits for conversion
private JsonConvertOptions.Builder convertOptionsBuilder;
// Handling access restrictions
private Restrictor restrictor;
// History handler
private HistoryStore historyStore;
// Storage for storing debug information
private DebugStore debugStore;
// Loghandler for dispatching logs
private LogHandler logHandler;
// List of RequestDispatchers to consult
private List<RequestDispatcher> requestDispatchers;
// Initialize used for late initialization
// ("volatile: because we use double-checked locking later on
// --> http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)
private volatile Initializer initializer;
// Details about the agent inclding the server handle
private AgentDetails agentDetails;
/**
* Construct a new backend manager with the given configuration and which allows
* every operation (no restrictor)
*
* @param pConfig configuration used for tuning this handler's behaviour
* @param pLogHandler logger
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler) {
this(pConfig, pLogHandler, null);
}
/**
* Construct a new backend manager with the given configuration.
*
* @param pConfig configuration used for tuning this handler's behaviour
* @param pLogHandler logger
* @param pRestrictor a restrictor for limiting access. Can be null in which case every operation is allowed
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler, Restrictor pRestrictor) {
this(pConfig,pLogHandler,pRestrictor,false);
}
/**
* Construct a new backend manager with the given configuration.
*
* @param pConfig configuration map used for tuning this handler's behaviour
* @param pLogHandler logger
* @param pRestrictor a restrictor for limiting access. Can be null in which case every operation is allowed
* @param pLazy whether the initialisation should be done lazy
*/
public BackendManager(Configuration pConfig, LogHandler pLogHandler, Restrictor pRestrictor, boolean pLazy) {
// Access restrictor
restrictor = pRestrictor != null ? pRestrictor : new AllowAllRestrictor();
// Log handler for putting out debug
logHandler = pLogHandler;
// Details about the agent, used for discovery
agentDetails = new AgentDetails(pConfig);
if (pLazy) {
initializer = new Initializer(pConfig);
} else {
init(pConfig);
initializer = null;
}
}
/**
* Handle a single JMXRequest. The response status is set to 200 if the request
* was successful
*
* @param pJmxReq request to perform
* @return the already converted answer.
* @throws InstanceNotFoundException
* @throws AttributeNotFoundException
* @throws ReflectionException
* @throws MBeanException
*/
public JSONObject handleRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException,
ReflectionException, MBeanException, IOException {
lazyInitIfNeeded();
boolean debug = isDebug();
long time = 0;
if (debug) {
time = System.currentTimeMillis();
}
JSONObject json;
try {
json = callRequestDispatcher(pJmxReq);
// Update global history store, add timestamp and possibly history information to the request
historyStore.updateAndAdd(pJmxReq,json);
json.put("status",200 /* success */);
} catch (NotChangedException exp) {
// A handled indicates that its value hasn't changed. We return an status with
//"304 Not Modified" similar to the HTTP status code (http://en.wikipedia.org/wiki/HTTP_status)
json = new JSONObject();
json.put("request",pJmxReq.toJSON());
json.put("status",304);
json.put("timestamp",System.currentTimeMillis() / 1000);
}
if (debug) {
debug("Execution time: " + (System.currentTimeMillis() - time) + " ms");
debug("Response: " + json);
}
return json;
}
/**
* Convert a Throwable to a JSON object so that it can be included in an error response
*
* @param pExp throwable to convert
* @param pJmxReq the request from where to take the serialization options
* @return the exception.
*/
public Object convertExceptionToJson(Throwable pExp, JmxRequest pJmxReq) {
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
try {
JSONObject expObj =
(JSONObject) converters.getToJsonConverter().convertToJson(pExp,null,opts);
return expObj;
} catch (AttributeNotFoundException e) {
// Cannot happen, since we dont use a path
return null;
}
}
/**
* Remove MBeans
*/
public void destroy() {
try {
localDispatcher.destroy();
} catch (JMException e) {
error("Cannot unregister MBean: " + e,e);
}
}
/**
* Check whether remote access from the given client is allowed.
*
* @param pRemoteHost remote host to check against
* @param pRemoteAddr alternative IP address
* @return true if remote access is allowed
*/
public boolean isRemoteAccessAllowed(String pRemoteHost, String pRemoteAddr) {
return restrictor.isRemoteAccessAllowed(pRemoteHost, pRemoteAddr);
}
/**
* Check whether CORS access is allowed for the given origin.
*
* @param pOrigin origin URL which needs to be checked
* @param pStrictChecking whether to a strict check (i.e. server side check)
* @return true if if cors access is allowed
*/
public boolean isOriginAllowed(String pOrigin,boolean pStrictChecking) {
return restrictor.isOriginAllowed(pOrigin, pStrictChecking);
}
/**
* Log at info level
*
* @param msg to log
*/
public void info(String msg) {
logHandler.info(msg);
if (debugStore != null) {
debugStore.log(msg);
}
}
/**
* Log at debug level
*
* @param msg message to log
*/
public void debug(String msg) {
logHandler.debug(msg);
if (debugStore != null) {
debugStore.log(msg);
}
}
/**
* Log at error level.
*
* @param message message to log
* @param t ecxeption occured
*/
public void error(String message, Throwable t) {
// Must not be final so that we can mock it in EasyMock for our tests
logHandler.error(message, t);
if (debugStore != null) {
debugStore.log(message, t);
}
}
/**
* Whether debug is switched on
*
* @return true if debug is switched on
*/
public boolean isDebug() {
return debugStore != null && debugStore.isDebug();
}
/**
* Get the details for the agent which can be updated or used
*
* @return agent details
*/
public AgentDetails getAgentDetails() {
return agentDetails;
}
// ==========================================================================================================
// Initialized used for late initialisation as it is required for the agent when used
// as startup options
private final class Initializer {
private Configuration config;
private Initializer(Configuration pConfig) {
config = pConfig;
}
void init() {
BackendManager.this.init(config);
}
}
// Run initialized if not already done
private void lazyInitIfNeeded() {
if (initializer != null) {
synchronized (this) {
if (initializer != null) {
initializer.init();
initializer = null;
}
}
}
}
// Initialize this object;
private void init(Configuration pConfig) {
// Central objects
converters = new Converters();
initLimits(pConfig);
// Create and remember request dispatchers
localDispatcher = new LocalRequestDispatcher(converters,
restrictor,
pConfig,
logHandler);
ServerHandle serverHandle = localDispatcher.getServerHandle();
requestDispatchers = createRequestDispatchers(pConfig.get(DISPATCHER_CLASSES),
converters,serverHandle,restrictor);
requestDispatchers.add(localDispatcher);
// Backendstore for remembering agent state
initMBeans(pConfig);
agentDetails.setServerInfo(serverHandle.getVendor(),serverHandle.getProduct(),serverHandle.getVersion());
}
private void initLimits(Configuration pConfig) {
// Max traversal depth
if (pConfig != null) {
convertOptionsBuilder = new JsonConvertOptions.Builder(
getNullSaveIntLimit(pConfig.get(MAX_DEPTH)),
getNullSaveIntLimit(pConfig.get(MAX_COLLECTION_SIZE)),
getNullSaveIntLimit(pConfig.get(MAX_OBJECTS))
);
} else {
convertOptionsBuilder = new JsonConvertOptions.Builder();
}
}
private int getNullSaveIntLimit(String pValue) {
return pValue != null ? Integer.parseInt(pValue) : 0;
}
// Construct configured dispatchers by reflection. Returns always
// a list, an empty one if no request dispatcher should be created
private List<RequestDispatcher> createRequestDispatchers(String pClasses,
Converters pConverters,
ServerHandle pServerHandle,
Restrictor pRestrictor) {
List<RequestDispatcher> ret = new ArrayList<RequestDispatcher>();
if (pClasses != null && pClasses.length() > 0) {
String[] names = pClasses.split("\\s*,\\s*");
for (String name : names) {
ret.add(createDispatcher(name, pConverters, pServerHandle, pRestrictor));
}
}
return ret;
}
// Create a single dispatcher
private RequestDispatcher createDispatcher(String pDispatcherClass,
Converters pConverters,
ServerHandle pServerHandle, Restrictor pRestrictor) {
try {
Class clazz = this.getClass().getClassLoader().loadClass(pDispatcherClass);
Constructor constructor = clazz.getConstructor(Converters.class,
ServerHandle.class,
Restrictor.class);
return (RequestDispatcher)
constructor.newInstance(pConverters,
pServerHandle,
pRestrictor);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Couldn't load class " + pDispatcherClass + ": " + e,e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + pDispatcherClass + " has invalid constructor: " + e,e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Constructor of " + pDispatcherClass + " couldn't be accessed: " + e,e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(pDispatcherClass + " couldn't be instantiated: " + e,e);
}
}
// call the an appropriate request dispatcher
private JSONObject callRequestDispatcher(JmxRequest pJmxReq)
throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException {
Object retValue = null;
boolean useValueWithPath = false;
boolean found = false;
for (RequestDispatcher dispatcher : requestDispatchers) {
if (dispatcher.canHandle(pJmxReq)) {
retValue = dispatcher.dispatchRequest(pJmxReq);
useValueWithPath = dispatcher.useReturnValueWithPath(pJmxReq);
found = true;
break;
}
}
if (!found) {
throw new IllegalStateException("Internal error: No dispatcher found for handling " + pJmxReq);
}
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
Object jsonResult =
converters.getToJsonConverter()
.convertToJson(retValue, useValueWithPath ? pJmxReq.getPathParts() : null, opts);
JSONObject jsonObject = new JSONObject();
jsonObject.put("value",jsonResult);
jsonObject.put("request",pJmxReq.toJSON());
return jsonObject;
}
private JsonConvertOptions getJsonConvertOptions(JmxRequest pJmxReq) {
return convertOptionsBuilder.
maxDepth(pJmxReq.getParameterAsInt(ConfigKey.MAX_DEPTH)).
maxCollectionSize(pJmxReq.getParameterAsInt(ConfigKey.MAX_COLLECTION_SIZE)).
maxObjects(pJmxReq.getParameterAsInt(ConfigKey.MAX_OBJECTS)).
faultHandler(pJmxReq.getValueFaultHandler()).
build();
}
// init various application wide stores for handling history and debug output.
private void initMBeans(Configuration pConfig) {
int maxEntries = pConfig.getAsInt(HISTORY_MAX_ENTRIES);
int maxDebugEntries = pConfig.getAsInt(DEBUG_MAX_ENTRIES);
historyStore = new HistoryStore(maxEntries);
debugStore = new DebugStore(maxDebugEntries, pConfig.getAsBoolean(DEBUG));
try {
localDispatcher.initMBeans(historyStore, debugStore);
} catch (NotCompliantMBeanException e) {
intError("Error registering config MBean: " + e, e);
} catch (MBeanRegistrationException e) {
intError("Cannot register MBean: " + e, e);
} catch (MalformedObjectNameException e) {
intError("Invalid name for config MBean: " + e, e);
}
}
// Final private error log for use in the constructor above
private void intError(String message,Throwable t) {
logHandler.error(message, t);
debugStore.log(message, t);
}
}
| ./CrossVul/dataset_final_sorted/CWE-352/java/good_2031_0 |
crossvul-java_data_good_2097_2 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.model.LoadStatistics;
import hudson.model.Messages;
import hudson.model.Node;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.FullDuplexHttpChannel;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.ManagementLink;
import hudson.model.NoFingerprintMatch;
import hudson.model.OverallLoadStatistics;
import hudson.model.Project;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroup;
import hudson.model.ViewGroupMixIn;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.Queue;
import hudson.model.WorkspaceCleanupThread;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.markup.MarkupFormatter;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import static hudson.Util.fixEmpty;
import static hudson.Util.fixNull;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.CLICommand;
import hudson.cli.CliEntryPoint;
import hudson.cli.CliManagerImpl;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.lifecycle.Lifecycle;
import hudson.logging.LogRecorderManager;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.markup.RawHtmlMarkupFormatter;
import hudson.remoting.Channel;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.StreamTaskListener;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import static hudson.init.InitMilestone.*;
import hudson.security.BasicAuthenticationFilter;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import static java.util.logging.Level.SEVERE;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Hudson whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Hudson.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Hudson.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Set of installed cluster nodes.
* <p>
* We use this field with copy-on-write semantics.
* This field has mutable list (to keep the serialization look clean),
* but it shall never be modified. Only new completely populated slave
* list can be set here.
* <p>
* The field name should be really {@code nodes}, but again the backward compatibility
* prevents us from renaming.
*/
protected volatile NodeList slaves;
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Hudson.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
/**
* Send the browser to the config page.
* use View to trim view/{default-view} from URL if possible
*/
@Override
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
String redirect = result.getUrl()+"configure";
List<Ancestor> ancestors = req.getAncestors();
for (int i = ancestors.size() - 1; i >= 0; i--) {
Object o = ancestors.get(i).getObject();
if (o instanceof View) {
redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
break;
}
}
return redirect;
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public Jenkins getInstance() {
return theInstance;
}
};
@CLIResolver
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP",e);
}
dnsMultiCast = new DNSMultiCast(this);
Timer timer = Trigger.timer;
if (timer != null) {
timer.scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5));
}
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c,StreamTaskListener.fromStdout());
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
l.onLoaded();
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Hudson by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() throws IOException {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/**
* Gets all the installed {@link SCMListener}s.
*/
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public MarkupFormatter getMarkupFormatter() {
return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE;
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Hudson.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
List<T> r = new ArrayList<T>();
Stack<ItemGroup> q = new Stack<ItemGroup>();
q.push(this);
while(!q.isEmpty()) {
ItemGroup<?> parent = q.pop();
for (Item i : parent.getItems()) {
if(type.isInstance(i)) {
if (i.hasPermission(Item.READ))
r.add(type.cast(i));
}
if(i instanceof ItemGroup)
q.push((ItemGroup)i);
}
}
return r;
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Hudson.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Hudson forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
final Collator collator = Collator.getInstance();
public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
}
});
return r;
}
@CLIResolver
public Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Hudson.
*/
public @CheckForNull Node getNode(String name) {
return slaves.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return slaves;
}
/**
* Adds one more {@link Node} to Hudson.
*/
public synchronized void addNode(Node n) throws IOException {
if(n==null) throw new IllegalArgumentException();
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
if(!nl.contains(n)) // defensive check
nl.add(n);
setNodes(nl);
}
/**
* Removes a {@link Node} from Hudson.
*/
public synchronized void removeNode(@Nonnull Node n) throws IOException {
Computer c = n.toComputer();
if (c!=null)
c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved()));
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
nl.remove(n);
setNodes(nl);
}
public void setNodes(List<? extends Node> nodes) throws IOException {
this.slaves = new NodeList(nodes);
updateComputerList();
trimLabels();
save();
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
private void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
if (!value.contains("${")) {
File d = new File(value);
if (!d.isDirectory() && (d.getParentFile() == null || !d.getParentFile().canWrite())) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
// XXX failure to use either ITEM_* variable might be an error too?
}
return FormValidation.ok(); // XXX assumes it will be OK after substitution, but can we be sure?
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItem(key); }
protected Collection<TopLevelItem> all() { return getItems(); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins,
* such as "http://localhost/jenkins/".
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link StaplerRequest#getRootPath()}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return
* This method returns null if this parameter is not configured by the user.
* The caller must gracefully deal with this situation.
* The returned URL will always have the trailing '/'.
* @since 1.66
* @see Descriptor#getCheckUrl(String)
* @see #getRootUrlFromRequest()
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/".
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is
* default setup or the actual url uses https) and you should use getRootUrl if
* you want to be sure you reflect user setup.
* See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
*
* @since 1.263
*/
public String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
StringBuilder buf = new StringBuilder();
buf.append(req.getScheme()+"://");
buf.append(req.getServerName());
if(req.getServerPort()!=80)
buf.append(':').append(req.getServerPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", getRootDir().getPath(),
"ITEM_ROOTDIR", item.getRootDir().getPath(),
"ITEM_FULLNAME", item.getFullName(), // legacy, deprecated
"ITEM_FULL_NAME", item.getFullName().replace(':','$')))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
public FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Hudson would have to have crumb in it to protect
* Hudson from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes
* in Hudson.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
markupFormatter = null;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.GUICE
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Hudson is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
this.numExecutors = n;
save();
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
public TopLevelItem getItem(String name) {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
*
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // XXX consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // XXX consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean)
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Hudson by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
for (View v : views)
v.onJobRenamed(job, oldName, newName);
save();
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
for (ItemListener l : ItemListener.all())
l.onDeleted(item);
items.remove(item.getName());
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
save();
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles(new FileFilter() {
public boolean accept(File child) {
return child.isDirectory() && Items.getConfigFile(child).exists();
}
});
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
// JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file
// and will get overwritten when reloading. Make a backup copy now, and re-add them later
NodeList oldSlaves = slaves;
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves == null) slaves = new NodeList();
clouds.setOwner(Jenkins.this);
// JENKINS-8043: re-add the slaves which were not saved into the config file
// and are now missing, but still connected.
if (oldSlaves != null) {
ArrayList<Node> newSlaves = new ArrayList<Node>(slaves);
for (Node n: oldSlaves) {
if (n instanceof EphemeralNode) {
if(!newSlaves.contains(n)) {
newSlaves.add(n);
}
}
}
setNodes(newSlaves);
}
}
});
for (final File subdir : subdirs) {
g.requires(loadHudson).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : slaves)
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Hudson and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null || !useSecurity)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null || !useSecurity)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
if(useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
jdks.clear();
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
if (timeout > 0) timeout += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < timeout)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return r;
}
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
securityRealm.doLogout(req, rsp);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
WebApp.get(servletContext).setApp(new JenkinsReloadFailed(e));
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,MasterComputer.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
private transient final Map<UUID,FullDuplexHttpChannel> duplexChannels = new HashMap<UUID, FullDuplexHttpChannel>();
/**
* Handles HTTP requests for duplex channels for CLI.
*/
public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
if (!"POST".equals(req.getMethod())) {
// for GET request, serve _cli.jelly, assuming this is a browser
checkPermission(READ);
req.getView(this,"_cli.jelly").forward(req,rsp);
return;
}
// do not require any permission to establish a CLI connection
// the actual authentication for the connecting Channel is done by CLICommand
UUID uuid = UUID.fromString(req.getHeader("Session"));
rsp.setHeader("Hudson-Duplex",""); // set the header so that the client would know
FullDuplexHttpChannel server;
if(req.getHeader("Side").equals("download")) {
duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) {
protected void main(Channel channel) throws IOException, InterruptedException {
// capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator()
channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION,getAuthentication());
channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(channel));
}
});
try {
server.download(req,rsp);
} finally {
duplexChannels.remove(uuid);
}
} else {
duplexChannels.get(uuid).upload(req,rsp);
}
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Hudson, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Hudson for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Hudson is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
}
}
}.start();
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
while (isQuietingDown
&& (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) {
Thread.sleep(5000);
}
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
doScript(req, rsp, req.getView(this, "_script.jelly"));
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
doScript(req, rsp, req.getView(this, "_scriptText.jelly"));
}
private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(ADMINISTER);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals("(Default)"))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists.
*/
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// XXX SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/cli")
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // XXX cleaner to refactor doJnlpJars into a URA
// XXX consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
* @return
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
* @return
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
* @return
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*/
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
}
/**
* Shortcut for {@code Hudson.getInstance().lookup.get(type)}
*/
public static <T> T lookup(Class<T> type) {
return Jenkins.getInstance().lookup.get(type);
}
/**
* Live view of recent {@link LogRecord}s produced by Hudson.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM = new XStream2();
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2 = (XStream2)XSTREAM;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
try {
InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Hudson.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Hudson is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Hudson, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems.
*/
public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter("flyweightSupport", true);
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
static {
XSTREAM.alias("jenkins",Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk",JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS!=null;
assert ADMINISTER!=null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_2097_2 |
crossvul-java_data_bad_4990_0 | /**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.common.localization;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.conf.ConfigDefaults;
import com.redhat.rhn.common.db.datasource.DataResult;
import com.redhat.rhn.common.db.datasource.ModeFactory;
import com.redhat.rhn.common.db.datasource.SelectMode;
import com.redhat.rhn.common.util.StringUtil;
import com.redhat.rhn.frontend.context.Context;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import java.text.Collator;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Localization service class to simplify the job for producing localized
* (translated) strings within the product.
*
* @version $Rev$
*/
public class LocalizationService {
/**
* DateFormat used by RHN database queries. Useful for converting RHN dates
* into java.util.Dates so they can be formatted based on Locale.
*/
public static final String RHN_DB_DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String RHN_CUSTOM_DATEFORMAT = "yyyy-MM-dd HH:mm:ss z";
private static Logger log = Logger.getLogger(LocalizationService.class);
private static Logger msgLogger = Logger
.getLogger("com.redhat.rhn.common.localization.messages");
public static final Locale DEFAULT_LOCALE = new Locale("EN", "US");
// private instance of the service.
private static LocalizationService instance = new LocalizationService();
// This Map stores the association of the java class names
// that map to the message keys found in the StringResources.xml
// files. This allows us to have sets of XML ResourceBundles that
// are specified in the rhn.jconf
private Map<String, String> keyToBundleMap;
// List of supported locales
private final Map<String, LocaleInfo> supportedLocales =
new HashMap<String, LocaleInfo>();
/**
* hidden constructor
*/
private LocalizationService() {
initService();
}
/**
* Initialize the set of strings and keys used by the service
*/
protected void initService() {
// If we are reloading, lets log it.
if (keyToBundleMap != null) {
// We want to note in the log that we are doing this
log.warn("Reloading XML StringResource files.");
XmlMessages.getInstance().resetBundleCache();
}
keyToBundleMap = new HashMap<String, String>();
// Get the list of configured classnames from the config file.
String[] packages = Config.get().getStringArray(
ConfigDefaults.WEB_L10N_RESOURCEBUNDLES);
for (int i = 0; i < packages.length; i++) {
addKeysToMap(packages[i]);
}
if (supportedLocales.size() > 0) {
supportedLocales.clear();
}
loadSupportedLocales();
}
/** Add the keys from the specified class to the Service's Map. */
private void addKeysToMap(String className) {
try {
Class z = Class.forName(className);
// All the keys must exist in the en_US XML files first. The other
// languages may have subsets but no unique keys. If this is a
// problem
// refactoring will need to take place.
Enumeration<String> e = XmlMessages.getInstance().getKeys(z, Locale.US);
while (e.hasMoreElements()) {
String key = e.nextElement();
keyToBundleMap.put(key, className);
}
}
catch (ClassNotFoundException ce) {
String message = "Class not found when trying to initalize " +
"the LocalizationService: " + ce.toString();
log.error(message, ce);
throw new LocalizationException(message, ce);
}
}
private void loadSupportedLocales() {
String rawLocales = Config.get().getString("java.supported_locales");
if (rawLocales == null) {
return;
}
List<String> compoundLocales = new LinkedList<String>();
for (Enumeration<Object> locales = new StringTokenizer(rawLocales, ","); locales
.hasMoreElements();) {
String locale = (String) locales.nextElement();
if (locale.indexOf('_') > -1) {
compoundLocales.add(locale);
}
LocaleInfo li = new LocaleInfo(locale);
this.supportedLocales.put(locale, li);
}
for (Iterator<String> iter = compoundLocales.iterator(); iter.hasNext();) {
String cl = iter.next();
String[] parts = cl.split("_");
LocaleInfo li = new LocaleInfo(parts[0], cl);
if (this.supportedLocales.get(parts[0]) == null) {
this.supportedLocales.put(parts[0], li);
}
}
}
/**
* Get the running instance of the LocalizationService
*
* @return The LocalizationService singleton
*/
public static LocalizationService getInstance() {
return instance;
}
/**
* Reload the resource files from the disk. Only works in development mode.
* @return boolean if we reloaded the files or not.
*/
public boolean reloadResourceFiles() {
if (Config.get().getBoolean("java.development_environment")) {
initService();
return true;
}
log.error("Tried to reload XML StringResource files but " +
"we aren't in java.development_environment mode");
return false;
}
/**
* Get a localized version of a String and let the service attempt to figure
* out the callee's locale.
* @param messageId The key of the message we are fetching
* @return Translated String
*/
public String getMessage(String messageId) {
Context ctx = Context.getCurrentContext();
return getMessage(messageId, ctx.getLocale(), new Object[0]);
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param locale The locale to use when fetching the string
* @return Translated String
*/
public String getMessage(String messageId, Locale locale) {
return getMessage(messageId, locale, new Object[0]);
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param args arguments for message.
* @return Translated String
*/
public String getMessage(String messageId, Object... args) {
Context ctx = Context.getCurrentContext();
return getMessage(messageId, ctx.getLocale(), args);
}
/**
* Gets a Plain Text + localized version of a string with the default locale.
* @param messageId The key of the message we are fetching
* @param args arguments for message.
* @return Translated String
*/
public String getPlainText(String messageId, Object... args) {
String msg = getMessage(messageId, args);
String unescaped = StringEscapeUtils.unescapeHtml(msg);
return StringUtil.toPlainText(unescaped);
}
/**
* Gets a Plain Text + localized version of a string with the default locale.
* @param messageId The key of the message we are fetching
* @return Translated String
*/
public String getPlainText(String messageId) {
return getPlainText(messageId, (Object[])null);
}
/**
* Take in a String array of keys and transform it into a String array of
* localized Strings.
* @param keys String[] array of key values
* @return String[] array of localized strings.
*/
public String[] getMessages(String[] keys) {
String[] retval = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
retval[i] = getMessage(keys[i]);
}
return retval;
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param locale The locale to use when fetching the string
* @param args arguments for message.
* @return Translated String
*/
public String getMessage(String messageId, Locale locale, Object... args) {
log.debug("getMessage() called with messageId: " + messageId +
" and locale: " + locale);
// Short-circuit the rest of the method if the messageId is null
// See bz 199892
if (messageId == null) {
return getMissingMessageString(messageId);
}
String userLocale = locale == null ? "null" : locale.toString();
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId +
"\" for locale " + userLocale);
}
String mess = null;
Class z = null;
try {
// If the keyMap doesn't contain the requested key
// then there is no hope and we return.
if (!keyToBundleMap.containsKey(messageId)) {
return getMissingMessageString(messageId);
}
z = Class.forName(keyToBundleMap.get(messageId));
// If we already determined that there aren't an bundles
// for this Locale then we shouldn't repeatedly fail
// attempts to parse the bundle. Instead just force a
// call to the default Locale.
mess = XmlMessages.getInstance().format(z, locale,
messageId, args);
}
catch (MissingResourceException e) {
// Try again with DEFAULT_LOCALE
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId +
"\" for locale " + userLocale +
" failed - trying again with default " + "locale " +
DEFAULT_LOCALE.toString());
}
try {
mess = XmlMessages.getInstance().format(z, DEFAULT_LOCALE,
messageId, args);
}
catch (MissingResourceException mre) {
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId + "\" " +
"for default locale " + DEFAULT_LOCALE.toString() +
" failed");
}
return getMissingMessageString(messageId);
}
}
catch (ClassNotFoundException ce) {
String message = "Class not found when trying to fetch a message: " +
ce.toString();
log.error(message, ce);
throw new LocalizationException(message, ce);
}
return getDebugVersionOfString(mess);
}
private String getDebugVersionOfString(String mess) {
// If we have put the Service into debug mode we
// will wrap all the messages in a marker.
boolean debugMode = Config.get().getBoolean("java.l10n_debug");
if (debugMode) {
StringBuilder debug = new StringBuilder();
String marker = Config.get().getString("java.l10n_debug_marker",
"$$$");
debug.append(marker);
debug.append(mess);
debug.append(marker);
mess = debug.toString();
}
return mess;
}
// returns the first class/method that does not belong to this
// package (who calls this actually) - for debugging purposes
private StackTraceElement getCallingMethod() {
try {
throw new RuntimeException("Stacktrace Dummy Exception");
}
catch (RuntimeException e) {
try {
final String prefix = this.getClass().getPackage().getName();
for (StackTraceElement element : e.getStackTrace()) {
if (!element.getClassName().startsWith(prefix)) {
return element;
}
}
}
catch (Throwable t) {
// dont break - return nothing rather than stop
return null;
}
}
return null;
}
private String getMissingMessageString(String messageId) {
String caller = "";
StackTraceElement callerElement = getCallingMethod();
if (callerElement != null) {
caller = " called by " + callerElement;
}
if (messageId == null) {
messageId = "null";
}
String message = "*** ERROR: Message with id: [" + messageId +
"] not found.***" + caller;
log.error(message);
boolean exceptionMode = Config.get().getBoolean(
"java.l10n_missingmessage_exceptions");
if (exceptionMode) {
throw new IllegalArgumentException(message);
}
return "**" + messageId + "**";
}
/**
* Get localized text for log messages as well as error emails. Determines
* Locale of running JVM vs using the current Thread or any other User
* related Locale information. TODO mmccune Get Locale out of Config or from
* the JVM
* @param messageId The key of the message we are fetching
* @return String debug message.
*/
public String getDebugMessage(String messageId) {
return getMessage(messageId, Locale.US);
}
/**
* Format the date and let the service determine the locale
* @param date Date to be formatted.
* @return String representation of given date.
*/
public String formatDate(Date date) {
Context ctx = Context.getCurrentContext();
return formatDate(date, ctx.getLocale());
}
/**
* Format the date as a short date depending on locale (YYYY-MM-DD in the
* US)
* @param date Date to be formatted
* @return String representation of given date.
*/
public String formatShortDate(Date date) {
Context ctx = Context.getCurrentContext();
return formatShortDate(date, ctx.getLocale());
}
/**
* Format the date as a short date depending on locale (YYYY-MM-DD in the
* US)
*
* @param date Date to be formatted
* @param locale Locale to use for formatting
* @return String representation of given date.
*/
public String formatShortDate(Date date, Locale locale) {
StringBuilder dbuff = new StringBuilder();
DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
dbuff.append(dateI.format(date));
return getDebugVersionOfString(dbuff.toString());
}
/**
* Use today's date and get it back localized and as a String
* @return String representation of today's date.
*/
public String getBasicDate() {
return formatDate(new Date());
}
/**
* Format the date based on the locale and convert it to a String to
* display. Uses DateFormat.SHORT. Example: 2004-12-10 13:20:00 PST
*
* Also includes the timezone of the current User if there is one
*
* @param date Date to format.
* @param locale Locale to use for formatting.
* @return String representation of given date in given locale.
*/
public String formatDate(Date date, Locale locale) {
// Example: 2004-12-10 13:20:00 PST
StringBuilder dbuff = new StringBuilder();
DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
dateI.setTimeZone(determineTimeZone());
DateFormat timeI = DateFormat.getTimeInstance(DateFormat.LONG, locale);
timeI.setTimeZone(determineTimeZone());
dbuff.append(dateI.format(date));
dbuff.append(" ");
dbuff.append(timeI.format(date));
return getDebugVersionOfString(dbuff.toString());
}
/**
* Returns fixed custom format string displayed for the determined timezone
* Example: 2010-04-01 15:04:24 CEST
*
* @param date Date to format.
* @return String representation of given date for set timezone
*/
public String formatCustomDate(Date date) {
TimeZone tz = determineTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat(RHN_CUSTOM_DATEFORMAT);
sdf.setTimeZone(tz);
return sdf.format(date);
}
/**
* Format the Number based on the locale and convert it to a String to
* display.
* @param numberIn Number to format.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn) {
Context ctx = Context.getCurrentContext();
return formatNumber(numberIn, ctx.getLocale());
}
/**
* Format the Number based on the locale and convert it to a String to
* display. Use a specified number of fraction digits.
* @param numberIn Number to format.
* @param fractionalDigits The number of fractional digits to use. This is
* both the minimum and maximum that will be displayed.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, int fractionalDigits) {
Context ctx = Context.getCurrentContext();
return formatNumber(numberIn, ctx.getLocale(), fractionalDigits);
}
/**
* Format the Number based on the locale and convert it to a String to
* display.
* @param numberIn Number to format.
* @param localeIn Locale to use for formatting.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, Locale localeIn) {
return getDebugVersionOfString(NumberFormat.getInstance(localeIn)
.format(numberIn));
}
/**
* Format the Number based on the locale and convert it to a String to
* display. Use a specified number of fractional digits.
* @param numberIn Number to format.
* @param localeIn Locale to use for formatting.
* @param fractionalDigits The maximum number of fractional digits to use.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, Locale localeIn,
int fractionalDigits) {
NumberFormat nf = NumberFormat.getInstance(localeIn);
nf.setMaximumFractionDigits(fractionalDigits);
return getDebugVersionOfString(nf.format(numberIn));
}
/**
* Get alphabet list for callee's Thread's Locale
* @return the list of alphanumeric characters from the alphabet
*/
public List<String> getAlphabet() {
return StringUtil.stringToList(getMessage("alphabet"));
}
/**
* Get digit list for callee's Thread's Locale
* @return the list of digits
*/
public List<String> getDigits() {
return StringUtil.stringToList(getMessage("digits"));
}
/**
* Get a list of available prefixes and ensure that it is sorted by
* returning a SortedSet object.
* @return SortedSet sorted set of available prefixes.
*/
public SortedSet<String> availablePrefixes() {
SelectMode prefixMode = ModeFactory.getMode("util_queries",
"available_prefixes");
// no params for this query
DataResult<Map<String, Object>> dr = prefixMode.execute(new HashMap());
SortedSet<String> ret = new TreeSet<String>();
Iterator<Map<String, Object>> i = dr.iterator();
while (i.hasNext()) {
Map<String, Object> row = i.next();
ret.add((String) row.get("prefix"));
}
return ret;
}
/**
* Get a SortedMap containing NAME/CODE value pairs. The reason we key the
* Map based on the NAME is that we desire to maintain a localized sort
* order based on the display value and not the code.
*
* <pre>
* {name=Spain, code=ES}
* {name=Sri Lanka, code=LK}
* {name=Sudan, code=SD}
* {name=Suriname, code=SR, }
* etc ...
* </pre>
*
* @return SortedMap sorted map of available countries.
*/
public SortedMap<String, String> availableCountries() {
List<String> validCountries = new LinkedList<String>(
Arrays.asList(Locale
.getISOCountries()));
String[] excluded = Config.get().getStringArray(
ConfigDefaults.WEB_EXCLUDED_COUNTRIES);
if (excluded != null) {
validCountries.removeAll(new LinkedList<String>(Arrays
.asList(excluded)));
}
SortedMap<String, String> ret = new TreeMap<String, String>();
for (Iterator<String> iter = validCountries.iterator(); iter.hasNext();) {
String isoCountry = iter.next();
ret.put(this.getMessage(isoCountry), isoCountry);
}
return ret;
}
/**
* Simple util method to determine if the
* @param messageId we are searching for
* @return boolean if we have loaded this message
*/
public boolean hasMessage(String messageId) {
return this.keyToBundleMap.containsKey(messageId);
}
/**
* Get list of supported locales in string form
* @return supported locales
*/
public List<String> getSupportedLocales() {
List<String> tmp = new LinkedList<String>(this.supportedLocales.keySet());
Collections.sort(tmp);
return Collections.unmodifiableList(tmp);
}
/**
* Returns the list of configured locales which is most likely a subset of
* all the supported locales
* @return list of configured locales
*/
public List<String> getConfiguredLocales() {
List<String> tmp = new LinkedList<String>();
for (Iterator<String> iter = this.supportedLocales.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
LocaleInfo li = this.supportedLocales.get(key);
if (!li.isAlias()) {
tmp.add(key);
}
}
Collections.sort(tmp);
return Collections.unmodifiableList(tmp);
}
/**
* Determines if locale is supported
* @param locale user's locale
* @return result
*/
public boolean isLocaleSupported(Locale locale) {
return this.supportedLocales.get(locale.toString()) != null;
}
/**
* Determine the Timezone from the Context. Uses TimeZone.getDefault() if
* there isn't one.
*
* @return TimeZone from the Context
*/
private TimeZone determineTimeZone() {
TimeZone retval = null;
Context ctx = Context.getCurrentContext();
if (ctx != null) {
retval = ctx.getTimezone();
}
if (retval == null) {
log.debug("Context is null");
// Get the app server's default timezone
retval = TimeZone.getDefault();
}
if (log.isDebugEnabled()) {
log.debug("Determined timeZone to be: " + retval);
}
return retval;
}
/**
* Returns a NEW instance of the collator/string comparator
* based on the current locale..
* Look at the javadoc for COllator to see what it does...
* (basically an i18n aware string comparator)
* @return neww instance of the collator
*/
public Collator newCollator() {
Context context = Context.getCurrentContext();
if (context != null && context.getLocale() != null) {
return Collator.getInstance(context.getLocale());
}
return Collator.getInstance();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_4990_0 |
crossvul-java_data_good_509_1 | package org.hswebframework.web.workflow.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ModelEntity;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.hswebframework.ezorm.core.PropertyWrapper;
import org.hswebframework.ezorm.core.SimplePropertyWrapper;
import org.hswebframework.ezorm.core.param.TermType;
import org.hswebframework.web.NotFoundException;
import org.hswebframework.web.authorization.Permission;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.workflow.enums.ModelType;
import org.hswebframework.web.workflow.util.QueryUtils;
import org.hswebframework.web.workflow.web.request.ModelCreateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/workflow/model")
@Api(tags = "工作流-模型管理", description = "工作流模型管理")
@Authorize(permission = "workflow-model", description = "工作流模型管理")
@Slf4j
public class FlowableModelManagerController {
@Autowired
private RepositoryService repositoryService;
private final static String MODEL_ID = "modelId";
private final static String MODEL_NAME = "name";
private final static String MODEL_REVISION = "revision";
private final static String MODEL_DESCRIPTION = "description";
private final static String MODEL_KEY = "key";
@GetMapping
@Authorize(action = Permission.ACTION_QUERY)
@ApiOperation("获取模型列表")
public ResponseMessage<PagerResult<Model>> getModelList(QueryParamEntity param) {
ModelQuery modelQuery = repositoryService.createModelQuery();
return ResponseMessage.ok(
QueryUtils.doQuery(modelQuery, param,
model -> FastBeanCopier.copy(model, new ModelEntity()),
(term, modelQuery1) -> {
if ("latestVersion".equals(term.getColumn())) {
modelQuery1.latestVersion();
}
}));
}
@PostMapping
@ResponseStatus(value = HttpStatus.CREATED)
@ApiOperation("创建模型")
public ResponseMessage<Model> createModel(@RequestBody ModelCreateRequest model) throws Exception {
JSONObject stencilset = new JSONObject();
stencilset.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
JSONObject editorNode = new JSONObject();
editorNode.put("id", "canvas");
editorNode.put("resourceId", "canvas");
editorNode.put("stencilset", stencilset);
JSONObject modelObjectNode = new JSONObject();
modelObjectNode.put(MODEL_REVISION, 1);
modelObjectNode.put(MODEL_DESCRIPTION, model.getDescription());
modelObjectNode.put(MODEL_KEY, model.getKey());
modelObjectNode.put(MODEL_NAME, model.getName());
Model modelData = repositoryService.newModel();
modelData.setMetaInfo(modelObjectNode.toJSONString());
modelData.setName(model.getName());
modelData.setKey(model.getKey());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
return ResponseMessage.ok(modelData).status(201);
}
@PostMapping("/{modelId}/deploy")
@ApiOperation("发布模型")
@Authorize(action = "deploy")
public ResponseMessage<Deployment> deployModel(@PathVariable String modelId) throws Exception {
Model modelData = repositoryService.getModel(modelId);
if (modelData == null) {
throw new NotFoundException("模型不存在!");
}
ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
String processName = modelData.getName() + ".bpmn20.xml";
Deployment deployment = repositoryService.createDeployment()
.name(modelData.getName())
.addString(processName, new String(bpmnBytes, "utf8"))
.deploy();
return ResponseMessage.ok(deployment).include(Deployment.class, "id", "name", "new");
}
/**
* 导出model对象为指定类型
*
* @param modelId 模型ID
* @param type 导出文件类型(bpmn\json)
*/
@GetMapping(value = "export/{modelId}/{type}")
@ApiOperation("导出模型")
@Authorize(action = "export")
@SneakyThrows
public void export(@PathVariable("modelId") @ApiParam("模型ID") String modelId,
@PathVariable("type") @ApiParam(value = "类型", allowableValues = "bpmn,json", example = "json")
ModelType type,
@ApiParam(hidden = true) HttpServletResponse response) {
Model modelData = repositoryService.getModel(modelId);
if (modelData == null) {
throw new NotFoundException("模型不存在");
}
BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());
JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
// 处理异常
if (bpmnModel.getMainProcess() == null) {
throw new UnsupportedOperationException("无法导出模型文件:" + type);
}
String filename = "";
byte[] exportBytes = null;
String mainProcessId = bpmnModel.getMainProcess().getId();
if (type == ModelType.bpmn) {
BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
exportBytes = xmlConverter.convertToXML(bpmnModel);
filename = mainProcessId + ".bpmn20.xml";
} else if (type == ModelType.json) {
exportBytes = modelEditorSource;
filename = mainProcessId + ".json";
} else {
throw new UnsupportedOperationException("不支持的格式:" + type);
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
/*创建输入流*/
try (ByteArrayInputStream in = new ByteArrayInputStream(exportBytes)) {
IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
}
}
@GetMapping(value = "/{modelId}/json")
@Authorize(action = Permission.ACTION_GET)
public Object getEditorJson(@PathVariable String modelId) {
JSONObject modelNode;
Model model = repositoryService.getModel(modelId);
if (model == null) throw new NullPointerException("模型不存在");
if (StringUtils.isNotEmpty(model.getMetaInfo())) {
modelNode = JSON.parseObject(model.getMetaInfo());
} else {
modelNode = new JSONObject();
modelNode.put(MODEL_NAME, model.getName());
}
modelNode.put(MODEL_ID, model.getId());
modelNode.put("model", JSON.parse(new String(repositoryService.getModelEditorSource(model.getId()))));
return modelNode;
}
@PutMapping(value = "/{modelId}")
@ResponseStatus(value = HttpStatus.OK)
@Authorize(action = Permission.ACTION_UPDATE)
public void saveModel(@PathVariable String modelId,
@RequestParam Map<String, String> values) throws TranscoderException, IOException {
Model model = repositoryService.getModel(modelId);
JSONObject modelJson = JSON.parseObject(model.getMetaInfo());
modelJson.put(MODEL_NAME, values.get("name"));
modelJson.put(MODEL_DESCRIPTION, values.get("description"));
model.setMetaInfo(modelJson.toString());
model.setName(values.get("name"));
repositoryService.saveModel(model);
repositoryService.addModelEditorSource(model.getId(), values.get("json_xml").getBytes("utf-8"));
InputStream svgStream = new ByteArrayInputStream(values.get("svg_xml").getBytes("utf-8"));
TranscoderInput input = new TranscoderInput(svgStream);
PNGTranscoder transcoder = new PNGTranscoder();
// Setup output
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(outStream);
// Do the transformation
transcoder.transcode(input, output);
final byte[] result = outStream.toByteArray();
repositoryService.addModelEditorSourceExtra(model.getId(), result);
outStream.close();
}
@DeleteMapping("/{modelId}")
@Authorize(action = Permission.ACTION_DELETE)
public ResponseMessage<Void> delete(@PathVariable String modelId) {
repositoryService.deleteModel(modelId);
return ResponseMessage.ok();
}
} | ./CrossVul/dataset_final_sorted/CWE-79/java/good_509_1 |
crossvul-java_data_bad_3049_0 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts,
* Yahoo! Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.EnvVars;
import hudson.Util;
import hudson.model.queue.SubTask;
import hudson.scm.SCM;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.util.VariableResolver;
import java.io.Serializable;
import java.util.Map;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* A value for a parameter in a build.
*
* Created by {@link ParameterDefinition#createValue(StaplerRequest, JSONObject)} for
* a particular build (although this 'owner' build object is passed in for every method
* call as a parameter so that the parameter won't have to persist it.)
*
* <h2>Persistence</h2>
* <p>
* Instances of {@link ParameterValue}s are persisted into build's <tt>build.xml</tt>
* through XStream (via {@link ParametersAction}), so instances need to be persistable.
*
* <h2>Associated Views</h2>
* <h4>value.jelly</h4>
* The <tt>value.jelly</tt> view contributes a UI fragment to display the parameter
* values used for a build.
*
* <h2>Notes</h2>
* <ol>
* <li>{@link ParameterValue} is used to record values of the past build, but
* {@link ParameterDefinition} used back then might be gone already, or represent
* a different parameter now. So don't try to use the name to infer
* {@link ParameterDefinition} is.
* </ol>
* @see ParameterDefinition
* @see ParametersAction
*/
@ExportedBean(defaultVisibility=3)
public abstract class ParameterValue implements Serializable {
protected final String name;
private String description;
protected ParameterValue(String name, String description) {
this.name = name;
this.description = description;
}
protected ParameterValue(String name) {
this(name, null);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Name of the parameter.
*
* This uniquely distinguishes {@link ParameterValue} among other parameters
* for the same build. This must be the same as {@link ParameterDefinition#getName()}.
*/
@Exported
public final String getName() {
return name;
}
/**
* Adds environmental variables for the builds to the given map.
*
* <p>
* This provides a means for a parameter to pass the parameter
* values to the build to be performed.
*
* <p>
* When this method is invoked, the map already contains the
* current "planned export" list. The implementation is
* expected to add more values to this map (or do nothing)
*
* <p>
* <strike>Environment variables should be by convention all upper case.
* (This is so that a Windows/Unix heterogeneous environment
* won't get inconsistent result depending on which platform to
* execute.)</strike> (see {@link EnvVars} why upper casing is a bad idea.)
*
* @param env
* never null.
* @param build
* The build for which this parameter is being used. Never null.
* @deprecated as of 1.344
* Use {@link #buildEnvironment(Run, EnvVars)} instead.
*/
@Deprecated
public void buildEnvVars(AbstractBuild<?,?> build, Map<String,String> env) {
if (env instanceof EnvVars) {
if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvironment", Run.class, EnvVars.class)) {
// if the subtype already derives buildEnvironment, then delegate to it
buildEnvironment(build, (EnvVars) env);
} else if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvVars", AbstractBuild.class, EnvVars.class)) {
buildEnvVars(build, (EnvVars) env);
}
}
// otherwise no-op by default
}
/** @deprecated Use {@link #buildEnvironment(Run, EnvVars)} instead. */
@Deprecated
public void buildEnvVars(AbstractBuild<?,?> build, EnvVars env) {
if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvironment", Run.class, EnvVars.class)) {
buildEnvironment(build, env);
} else {
// for backward compatibility
buildEnvVars(build,(Map<String,String>)env);
}
}
/**
* Adds environmental variables for the builds to the given map.
*
* <p>
* This provides a means for a parameter to pass the parameter
* values to the build to be performed.
*
* <p>
* When this method is invoked, the map already contains the
* current "planned export" list. The implementation is
* expected to add more values to this map (or do nothing)
*
* @param env
* never null.
* @param build
* The build for which this parameter is being used. Never null.
* @since 1.556
*/
public void buildEnvironment(Run<?,?> build, EnvVars env) {
if (build instanceof AbstractBuild) {
buildEnvVars((AbstractBuild) build, env);
}
// else do not know how to do it
}
/**
* Called at the beginning of a build (but after {@link SCM} operations
* have taken place) to let a {@link ParameterValue} contributes a
* {@link BuildWrapper} to the build.
*
* <p>
* This provides a means for a parameter to perform more extensive
* set up / tear down during a build.
*
* @param build
* The build for which this parameter is being used. Never null.
* @return
* null if the parameter has no {@link BuildWrapper} to contribute to.
*/
public BuildWrapper createBuildWrapper(AbstractBuild<?,?> build) {
return null;
}
/**
* Returns a {@link VariableResolver} so that other components like {@link Builder}s
* can perform variable substitution to reflect parameter values into the build process.
*
* <p.
* This is yet another means in which a {@link ParameterValue} can influence
* a build.
*
* @param build
* The build for which this parameter is being used. Never null.
* @return
* if the parameter value is not interested in participating to the
* variable replacement process, return {@link VariableResolver#NONE}.
*/
public VariableResolver<String> createVariableResolver(AbstractBuild<?,?> build) {
return VariableResolver.NONE;
}
// TODO should there be a Run overload of this?
/**
* Accessing {@link ParameterDefinition} is not a good idea.
*
* @deprecated since 2008-09-20.
* parameter definition may change any time. So if you find yourself
* in need of accessing the information from {@link ParameterDefinition},
* instead copy them in {@link ParameterDefinition#createValue(StaplerRequest, JSONObject)}
* into {@link ParameterValue}.
*/
@Deprecated
public ParameterDefinition getDefinition() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParameterValue other = (ParameterValue) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/**
* Computes a human-readable possible-localized one-line description of the parameter value.
*
* <P>
* This message is used as a tooltip to describe jobs in the queue. The text should be one line without
* new line. No HTML allowed (the caller will perform necessary HTML escapes, so any text can be returend.)
*
* @since 1.323
*/
public String getShortDescription() {
return toString();
}
/**
* Returns whether the information contained in this ParameterValue is
* sensitive or security related. Used to determine whether the value
* provided by this object should be masked in output.
*
* <p>
* Subclasses can override this to control the return value.
*
* @since 1.378
*/
public boolean isSensitive() {
return false;
}
/**
* Returns the most natural Java object that represents the actual value, like
* boolean, string, etc.
*
* If there's nothing that really fits the bill, the callee can return {@code this}.
* @since 1.568
*/
public Object getValue() {
return null;
}
/**
* Controls where the build (that this parameter is submitted to) will happen.
*
* @return
* null to run the build where it normally runs. If non-null, this will
* override {@link AbstractProject#getAssignedLabel()}. If a build is
* submitted with multiple parameters, the first one that returns non-null
* from this method will win, and all others won't be consulted.
*
*
* @since 1.414
*/
public Label getAssignedLabel(SubTask task) {
return null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_3049_0 |
crossvul-java_data_bad_2083_1 | /*
* Copyright 2002-2013 the original author or authors.
*
* 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 org.springframework.web.servlet.tags.form;
import java.util.Collections;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.mockito.BDDMockito.*;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
* @author Scott Andrews
* @author Jeremy Grelle
* @author Rossen Stoyanchev
*/
public class FormTagTests extends AbstractHtmlElementTagTests {
private static final String REQUEST_URI = "/my/form";
private static final String QUERY_STRING = "foo=bar";
private FormTag tag;
private MockHttpServletRequest request;
@Override
@SuppressWarnings("serial")
protected void onSetUp() {
this.tag = new FormTag() {
@Override
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
@Override
protected void extendRequest(MockHttpServletRequest request) {
request.setRequestURI(REQUEST_URI);
request.setQueryString(QUERY_STRING);
this.request = request;
}
public void testWriteForm() throws Exception {
String commandName = "myCommand";
String name = "formName";
String action = "/form.html";
String method = "POST";
String target = "myTarget";
String enctype = "my/enctype";
String acceptCharset = "iso-8859-1";
String onsubmit = "onsubmit";
String onreset = "onreset";
String autocomplete = "off";
String cssClass = "myClass";
String cssStyle = "myStyle";
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
this.tag.setName(name);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setCommandName(commandName);
this.tag.setAction(action);
this.tag.setMethod(method);
this.tag.setTarget(target);
this.tag.setEnctype(enctype);
this.tag.setAcceptCharset(acceptCharset);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
this.tag.setAutocomplete(autocomplete);
this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "class", cssClass);
assertContainsAttribute(output, "style", cssStyle);
assertContainsAttribute(output, "action", action);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "target", target);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "accept-charset", acceptCharset);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertContainsAttribute(output, "autocomplete", autocomplete);
assertContainsAttribute(output, "id", commandName);
assertContainsAttribute(output, "name", name);
assertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1);
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testWithActionFromRequest() throws Exception {
String commandName = "myCommand";
String enctype = "my/enctype";
String method = "POST";
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "action", REQUEST_URI + "?" + QUERY_STRING);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertAttributeNotPresent(output, "name");
}
public void testPrependServletPath() throws Exception {
this.request.setContextPath("/myApp");
this.request.setServletPath("/main");
this.request.setPathInfo("/index.html");
String commandName = "myCommand";
String action = "/form.html";
String enctype = "my/enctype";
String method = "POST";
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setServletRelativeAction(action);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "action", "/myApp/main/form.html");
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertAttributeNotPresent(output, "name");
}
public void testWithNullResolvedCommand() throws Exception {
try {
tag.setCommandName(null);
tag.doStartTag();
fail("Must not be able to have a command name that resolves to null");
}
catch (IllegalArgumentException ex) {
// expected
}
}
/*
* See http://opensource.atlassian.com/projects/spring/browse/SPR-2645
*/
public void testXSSScriptingExploitWhenActionIsResolvedFromQueryString() throws Exception {
String xssQueryString = QUERY_STRING + "&stuff=\"><script>alert('XSS!')</script>";
request.setQueryString(xssQueryString);
tag.doStartTag();
assertEquals("<form id=\"command\" action=\"/my/form?foo=bar&stuff="><script>alert('XSS!')</script>\" method=\"post\">",
getOutput());
}
public void testGet() throws Exception {
this.tag.setMethod("get");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "get");
assertEquals("", inputOutput);
}
public void testPost() throws Exception {
this.tag.setMethod("post");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertEquals("", inputOutput);
}
public void testPut() throws Exception {
this.tag.setMethod("put");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "_method");
assertContainsAttribute(inputOutput, "value", "put");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testDelete() throws Exception {
this.tag.setMethod("delete");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "_method");
assertContainsAttribute(inputOutput, "value", "delete");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testCustomMethodParameter() throws Exception {
this.tag.setMethod("put");
this.tag.setMethodParam("methodParameter");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "methodParameter");
assertContainsAttribute(inputOutput, "value", "put");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testClearAttributesOnFinally() throws Exception {
this.tag.setModelAttribute("model");
getPageContext().setAttribute("model", "foo bar");
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
this.tag.doStartTag();
assertNotNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
this.tag.doFinally();
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testRequestDataValueProcessorHooks() throws Exception {
String action = "/my/form?foo=bar";
RequestDataValueProcessor processor = getMockRequestDataValueProcessor();
given(processor.processAction(this.request, action, "post")).willReturn(action);
given(processor.getExtraHiddenFields(this.request)).willReturn(Collections.singletonMap("key", "value"));
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
assertEquals("<div>\n<input type=\"hidden\" name=\"key\" value=\"value\" />\n</div>", getInputTag(output));
assertFormTagOpened(output);
assertFormTagClosed(output);
}
private String getFormTag(String output) {
int inputStart = output.indexOf("<", 1);
int inputEnd = output.lastIndexOf(">", output.length() - 2);
return output.substring(0, inputStart) + output.substring(inputEnd + 1);
}
private String getInputTag(String output) {
int inputStart = output.indexOf("<", 1);
int inputEnd = output.lastIndexOf(">", output.length() - 2);
return output.substring(inputStart, inputEnd + 1);
}
private static void assertFormTagOpened(String output) {
assertTrue(output.startsWith("<form "));
}
private static void assertFormTagClosed(String output) {
assertTrue(output.endsWith("</form>"));
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_2083_1 |
crossvul-java_data_bad_5841_0 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.core;
import java.util.Collection;
import org.apache.commons.lang.ObjectUtils;
public class JsonBuilder
{
final private StringBuilder sb = new StringBuilder();
/**
* Creates Json result string from the given list.<br/>
* [["Horst"], ["Klaus"], ...]] // For single property<br/>
* [["Klein", "Horst"],["Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) [["id:37", "Klein", "Horst"],["id:42",
* "Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) with id. <br/>
* Uses ObjectUtils.toString(Object) for formatting each value.
* @param col The array representation: List<Object> or List<Object[]>. If null then "[]" is returned.
* @return
*/
public static String buildToStringRows(final Collection< ? > col)
{
if (col == null) {
return "[]";
}
final JsonBuilder builder = new JsonBuilder();
return builder.append(col).getAsString();
}
public String getAsString()
{
return sb.toString();
}
/**
* Appends objects to buffer, e. g.: ["Horst"], ["Klaus"], ... Uses formatValue(Object) to render the values.
* @param oArray
* @return This (fluent)
*/
public JsonBuilder append(final Object[] oArray)
{
sb.append(" ["); // begin array
String separator = "";
for (final Object obj : oArray) {
sb.append(separator);
separator = ",";
sb.append(escapeString(formatValue(obj)));
}
sb.append("]"); // end array
return this;
}
private String escapeString(final String string)
{
if (string == null || string.length() == 0) {
return "\"\"";
}
char c = 0;
int i;
final int len = string.length();
final StringBuilder sb = new StringBuilder(len + 4);
String t;
sb.append('"');
for (i = 0; i < len; i += 1) {
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
// if (b == '<') {
sb.append('\\');
// }
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ') {
t = "000" + Integer.toHexString(c);
sb.append("\\u" + t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
/**
* Creates Json result string from the given list.<br/>
* [["Horst"], ["Klaus"], ...]] // For single property<br/>
* [["Klein", "Horst"],["Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) [["id:37", "Klein", "Horst"],["id:42",
* "Schmidt", "Klaus"], ...] // For two Properties (e. g. name, first name) with id. <br/>
* Uses formatValue(Object) for formatting each value.
* @param col The array representation: List<Object> or List<Object[]>. If null then "[]" is returned.
* @return
*/
public JsonBuilder append(final Collection< ? > col)
{
if (col == null) {
sb.append("[]");
return this;
}
// Format: [["1.1", "1.2", ...],["2.1", "2.2", ...]]
sb.append("[\n");
String separator = "\n";
for (final Object os : col) {
sb.append(separator);
separator = ",\n";
if (os instanceof Object[]) { // Multiple properties
append((Object[]) os);
} else { // Only one property
append(transform(os));
}
}
sb.append("]"); // end data
return this;
}
/**
* @param obj
* @return
* @see ObjectUtils#toString(Object)
*/
protected String formatValue(final Object obj)
{
return ObjectUtils.toString(obj);
}
protected JsonBuilder append(final Object obj)
{
if (obj instanceof Object[]) {
return append((Object[]) obj);
}
sb.append(" ["); // begin row
// " must be quoted as \":
sb.append(escapeString(formatValue(obj)));
sb.append("]"); // end row
return this;
}
/**
* Before rendering a obj of e. g. a collection the obj can be transformed e. g. in an Object array of dimension 2 containing label and
* value.
* @param obj
* @return obj (identity function) if not overload.
*/
protected Object transform(final Object obj)
{
return obj;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_5841_0 |
crossvul-java_data_bad_1165_1 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.lifecycle;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.CLIENT_WINDOW_PARAM;
import java.util.Map;
import java.util.regex.Pattern;
import javax.faces.component.UINamingContainer;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.ResponseStateManager;
import javax.faces.FacesException;
public class ClientWindowImpl extends ClientWindow {
String id;
public ClientWindowImpl() {
}
@Override
public Map<String, String> getQueryURLParameters(FacesContext context) {
return null;
}
@Override
public void decode(FacesContext context) {
Map<String, String> requestParamMap = context.getExternalContext().getRequestParameterMap();
if (isClientWindowRenderModeEnabled(context)) {
id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_URL_PARAM);
}
// The hidden field always takes precedence, if present.
String paramName = CLIENT_WINDOW_PARAM.getName(context);
if (requestParamMap.containsKey(paramName)) {
id = requestParamMap.get(paramName);
Pattern safePattern = Pattern.compile(".*<(.*:script|script).*>[^&]*</\\s*\\1\\s*>.*");
if (safePattern.matcher(id).matches()) {
throw new FacesException("ClientWindow is illegal: " + id);
}
}
if (null == id) {
id = calculateClientWindow(context);
}
}
private String calculateClientWindow(FacesContext context) {
synchronized(context.getExternalContext().getSession(true)) {
final String clientWindowCounterKey = "com.sun.faces.lifecycle.ClientWindowCounterKey";
ExternalContext extContext = context.getExternalContext();
Map<String, Object> sessionAttrs = extContext.getSessionMap();
Integer counter = (Integer) sessionAttrs.get(clientWindowCounterKey);
if (null == counter) {
counter = Integer.valueOf(0);
}
char sep = UINamingContainer.getSeparatorChar(context);
id = extContext.getSessionId(true) + sep +
+ counter;
sessionAttrs.put(clientWindowCounterKey, ++counter);
}
return id;
}
@Override
public String getId() {
return id;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_1165_1 |
crossvul-java_data_good_1166_0 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.context;
import com.sun.faces.component.visit.PartialVisitContext;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitHint;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;
import java.io.Writer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;
import javax.faces.FactoryFinder;
import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.component.visit.VisitContextWrapper;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
public class PartialViewContextImpl extends PartialViewContext {
// Log instance for this class
private static Logger LOGGER = FacesLogger.CONTEXT.getLogger();
private boolean released;
// BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD
private PartialResponseWriter partialResponseWriter;
private List<String> executeIds;
private Collection<String> renderIds;
private Boolean ajaxRequest;
private Boolean partialRequest;
private Boolean renderAll;
private FacesContext ctx;
private boolean processingPhases = false;
private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER";
// ----------------------------------------------------------- Constructors
public PartialViewContextImpl(FacesContext ctx) {
this.ctx = ctx;
}
// ---------------------------------------------- Methods from PartialViewContext
/**
* @see javax.faces.context.PartialViewContext#isAjaxRequest()
*/
@Override
public boolean isAjaxRequest() {
assertNotReleased();
if (ajaxRequest == null) {
ajaxRequest = "partial/ajax".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
if (!ajaxRequest) {
ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap().
get("Faces-Request"));
}
}
return ajaxRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isPartialRequest()
*/
@Override
public boolean isPartialRequest() {
assertNotReleased();
if (partialRequest == null) {
partialRequest = isAjaxRequest() ||
"partial/process".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
}
return partialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isExecuteAll()
*/
@Override
public boolean isExecuteAll() {
assertNotReleased();
String execute = ctx.
getExternalContext().getRequestParameterMap()
.get(PARTIAL_EXECUTE_PARAM_NAME);
return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute));
}
/**
* @see javax.faces.context.PartialViewContext#isRenderAll()
*/
@Override
public boolean isRenderAll() {
assertNotReleased();
if (renderAll == null) {
String render = ctx.
getExternalContext().getRequestParameterMap()
.get(PARTIAL_RENDER_PARAM_NAME);
renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render));
}
return renderAll;
}
/**
* @see javax.faces.context.PartialViewContext#setRenderAll(boolean)
*/
@Override
public void setRenderAll(boolean renderAll) {
this.renderAll = renderAll;
}
@Override
public boolean isResetValues() {
Object value = ctx.getExternalContext().getRequestParameterMap().get(RESET_VALUES_PARAM_NAME);
return (null != value && "true".equals(value)) ? true : false;
}
@Override
public void setPartialRequest(boolean isPartialRequest) {
this.partialRequest = isPartialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#getExecuteIds()
*/
@Override
public Collection<String> getExecuteIds() {
assertNotReleased();
if (executeIds != null) {
return executeIds;
}
executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM_NAME);
// include the view parameter facet ID if there are other execute IDs
// to process
if (!executeIds.isEmpty()) {
UIViewRoot root = ctx.getViewRoot();
if (root.getFacetCount() > 0) {
if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) {
executeIds.add(0, UIViewRoot.METADATA_FACET_NAME);
}
}
}
return executeIds;
}
/**
* @see javax.faces.context.PartialViewContext#getRenderIds()
*/
@Override
public Collection<String> getRenderIds() {
assertNotReleased();
if (renderIds != null) {
return renderIds;
}
renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM_NAME);
return renderIds;
}
/**
* @see PartialViewContext#processPartial(javax.faces.event.PhaseId)
*/
@Override
public void processPartial(PhaseId phaseId) {
PartialViewContext pvc = ctx.getPartialViewContext();
Collection <String> myExecuteIds = pvc.getExecuteIds();
Collection <String> myRenderIds = pvc.getRenderIds();
UIViewRoot viewRoot = ctx.getViewRoot();
if (phaseId == PhaseId.APPLY_REQUEST_VALUES ||
phaseId == PhaseId.PROCESS_VALIDATIONS ||
phaseId == PhaseId.UPDATE_MODEL_VALUES) {
// Skip this processing if "none" is specified in the render list,
// or there were no execute phase client ids.
if (myExecuteIds == null || myExecuteIds.isEmpty()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"No execute and render identifiers specified. Skipping component processing.");
}
return;
}
try {
processComponents(viewRoot, phaseId, myExecuteIds, ctx);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO,
e.toString(),
e);
}
throw new FacesException(e);
}
// If we have just finished APPLY_REQUEST_VALUES phase, install the
// partial response writer. We want to make sure that any content
// or errors generated in the other phases are written using the
// partial response writer.
//
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ctx.setResponseWriter(writer);
}
} else if (phaseId == PhaseId.RENDER_RESPONSE) {
try {
//
// We re-enable response writing.
//
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ResponseWriter orig = ctx.getResponseWriter();
ctx.getAttributes().put(ORIGINAL_WRITER, orig);
ctx.setResponseWriter(writer);
ExternalContext exContext = ctx.getExternalContext();
exContext.setResponseContentType("text/xml");
exContext.addResponseHeader("Cache-Control", "no-cache");
// String encoding = writer.getCharacterEncoding( );
// if( encoding == null ) {
// encoding = "UTF-8";
// }
// writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n");
writer.startDocument();
if (isResetValues()) {
viewRoot.resetValues(ctx, myRenderIds);
}
if (isRenderAll()) {
renderAll(ctx, viewRoot);
renderState(ctx);
writer.endDocument();
return;
}
// Skip this processing if "none" is specified in the render list,
// or there were no render phase client ids.
if (myRenderIds != null && !myRenderIds.isEmpty()) {
processComponents(viewRoot, phaseId, myRenderIds, ctx);
}
renderState(ctx);
writer.endDocument();
} catch (IOException ex) {
this.cleanupAfterView();
} catch (RuntimeException ex) {
this.cleanupAfterView();
// Throw the exception
throw ex;
}
}
}
/**
* @see javax.faces.context.PartialViewContext#getPartialResponseWriter()
*/
@Override
public PartialResponseWriter getPartialResponseWriter() {
assertNotReleased();
if (partialResponseWriter == null) {
partialResponseWriter = new DelayedInitPartialResponseWriter(this);
}
return partialResponseWriter;
}
/**
* @see javax.faces.context.PartialViewContext#release()
*/
public void release() {
released = true;
ajaxRequest = null;
renderAll = null;
partialResponseWriter = null;
executeIds = null;
renderIds = null;
ctx = null;
partialRequest = null;
}
// -------------------------------------------------------- Private Methods
private List<String> populatePhaseClientIds(String parameterName) {
Map<String,String> requestParamMap =
ctx.getExternalContext().getRequestParameterMap();
String param = requestParamMap.get(parameterName);
if (param == null) {
return new ArrayList<String>();
} else {
Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
String[] pcs = Util.split(appMap, param, "[ \t]+");
return ((pcs != null && pcs.length != 0)
? new ArrayList<String>(Arrays.asList(pcs))
: new ArrayList<String>());
}
}
// Process the components specified in the phaseClientIds list
private void processComponents(UIComponent component, PhaseId phaseId,
Collection<String> phaseClientIds, FacesContext context) throws IOException {
// We use the tree visitor mechanism to locate the components to
// process. Create our (partial) VisitContext and the
// VisitCallback that will be invoked for each component that
// is visited. Note that we use the SKIP_UNRENDERED hint as we
// only want to visit the rendered subtree.
EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE);
VisitContextFactory visitContextFactory = (VisitContextFactory)
FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY);
VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints);
PhaseAwareVisitCallback visitCallback =
new PhaseAwareVisitCallback(ctx, phaseId);
component.visitTree(visitContext, visitCallback);
PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext);
if (partialVisitContext != null) {
if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) {
Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds();
String message;
StringBuilder builder = new StringBuilder();
for (String cur : unvisitedClientIds) {
builder.append(cur).append(" ");
}
LOGGER.log(Level.FINER,
"jsf.context.partial_visit_context_unvisited_children",
new Object[]{builder.toString()});
}
}
}
/**
* Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s.
*
* If no {@link PartialVisitContext} is found in the chain, null is returned instead.
*
* @param visitContext the visit context.
* @return the (unwrapped) partial visit context.
*/
private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) {
if (visitContext == null) {
return null;
}
if (visitContext instanceof PartialVisitContext) {
return (PartialVisitContext) visitContext;
}
if (visitContext instanceof VisitContextWrapper) {
return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped());
}
return null;
}
private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException {
// If this is a "render all via ajax" request,
// make sure to wrap the entire page in a <render> elemnt
// with the special viewStateId of VIEW_ROOT_ID. This is how the client
// JavaScript knows how to replace the entire document with
// this response.
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
if (!Util.isPortletRequest(context)) {
writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
writer.endUpdate();
}
else {
/*
* If we have a portlet request, start rendering at the view root.
*/
writer.startUpdate(viewRoot.getClientId(ctx));
viewRoot.encodeBegin(context);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
viewRoot.encodeEnd(context);
writer.endUpdate();
}
}
private void renderState(FacesContext context) throws IOException {
// Get the view state and write it to the response..
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
String viewStateId = Util.getViewStateId(context);
writer.startUpdate(viewStateId);
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
writer.endUpdate();
ClientWindow window = context.getExternalContext().getClientWindow();
if (null != window) {
String clientWindowId = Util.getClientWindowId(context);
writer.startUpdate(clientWindowId);
writer.writeText(window.getId(), null);
writer.endUpdate();
}
}
private PartialResponseWriter createPartialResponseWriter() {
ExternalContext extContext = ctx.getExternalContext();
String encoding = extContext.getRequestCharacterEncoding();
extContext.setResponseCharacterEncoding(encoding);
ResponseWriter responseWriter = null;
Writer out = null;
try {
out = extContext.getResponseOutputWriter();
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
}
if (out != null) {
UIViewRoot viewRoot = ctx.getViewRoot();
if (viewRoot != null) {
responseWriter =
ctx.getRenderKit().createResponseWriter(out,
"text/xml", encoding);
} else {
RenderKitFactory factory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);
responseWriter = renderKit.createResponseWriter(out, "text/xml", encoding);
}
}
if (responseWriter instanceof PartialResponseWriter) {
return (PartialResponseWriter) responseWriter;
} else {
return new PartialResponseWriter(responseWriter);
}
}
private void cleanupAfterView() {
ResponseWriter orig = (ResponseWriter) ctx.getAttributes().
get(ORIGINAL_WRITER);
assert(null != orig);
// move aside the PartialResponseWriter
ctx.setResponseWriter(orig);
}
@SuppressWarnings({"FinalPrivateMethod"})
private final void assertNotReleased() {
if (released) {
throw new IllegalStateException();
}
}
// ----------------------------------------------------------- Inner Classes
private static class PhaseAwareVisitCallback implements VisitCallback {
private PhaseId curPhase;
private FacesContext ctx;
private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) {
this.ctx = ctx;
this.curPhase = curPhase;
}
public VisitResult visit(VisitContext context, UIComponent comp) {
try {
if (curPhase == PhaseId.APPLY_REQUEST_VALUES) {
// RELEASE_PENDING handle immediate request(s)
// If the user requested an immediate request
// Make sure to set the immediate flag here.
comp.processDecodes(ctx);
} else if (curPhase == PhaseId.PROCESS_VALIDATIONS) {
comp.processValidators(ctx);
} else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) {
comp.processUpdates(ctx);
} else if (curPhase == PhaseId.RENDER_RESPONSE) {
PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter();
writer.startUpdate(comp.getClientId(ctx));
// do the default behavior...
comp.encodeAll(ctx);
writer.endUpdate();
} else {
throw new IllegalStateException("I18N: Unexpected " +
"PhaseId passed to " +
" PhaseAwareContextCallback: " +
curPhase.toString());
}
}
catch (IOException ex) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe(ex.toString());
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ex.toString(),
ex);
}
throw new FacesException(ex);
}
// Once we visit a component, there is no need to visit
// its children, since processDecodes/Validators/Updates and
// encodeAll() already traverse the subtree. We return
// VisitResult.REJECT to supress the subtree visit.
return VisitResult.REJECT;
}
}
/**
* Delays the actual construction of the PartialResponseWriter <em>until</em>
* content is going to actually be written.
*/
private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter {
private ResponseWriter writer;
private PartialViewContextImpl ctx;
// -------------------------------------------------------- Constructors
public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) {
super(null);
this.ctx = ctx;
ExternalContext extCtx = ctx.ctx.getExternalContext();
extCtx.setResponseContentType("text/xml");
extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding());
}
// ---------------------------------- Methods from PartialResponseWriter
@Override
public ResponseWriter getWrapped() {
if (writer == null) {
writer = ctx.createPartialResponseWriter();
}
return writer;
}
} // END DelayedInitPartialResponseWriter
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_1166_0 |
crossvul-java_data_good_2099_0 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Michael B. Donohue, Seiji Sogabe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import hudson.console.ModelHyperlinkNote;
import hudson.diagnosis.OldDataMonitor;
import hudson.util.XStream2;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Cause object base class. This class hierarchy is used to keep track of why
* a given build was started. This object encapsulates the UI rendering of the cause,
* as well as providing more useful information in respective subypes.
*
* The Cause object is connected to a build via the {@link CauseAction} object.
*
* <h2>Views</h2>
* <dl>
* <dt>description.jelly
* <dd>Renders the cause to HTML. By default, it puts the short description.
* </dl>
*
* @author Michael Donohue
* @see Run#getCauses()
* @see Queue.Item#getCauses()
*/
@ExportedBean
public abstract class Cause {
/**
* One-line human-readable text of the cause.
*
* <p>
* By default, this method is used to render HTML as well.
*/
@Exported(visibility=3)
public abstract String getShortDescription();
/**
* Called when the cause is registered to {@link AbstractBuild}.
*
* @param build
* never null
* @since 1.376
*/
public void onAddedTo(AbstractBuild build) {}
/**
* Report a line to the listener about this cause.
* @since 1.362
*/
public void print(TaskListener listener) {
listener.getLogger().println(getShortDescription());
}
/**
* Fall back implementation when no other type is available.
* @deprecated since 2009-02-08
*/
public static class LegacyCodeCause extends Cause {
private StackTraceElement [] stackTrace;
public LegacyCodeCause() {
stackTrace = new Exception().getStackTrace();
}
@Override
public String getShortDescription() {
return Messages.Cause_LegacyCodeCause_ShortDescription();
}
}
/**
* A build is triggered by the completion of another build (AKA upstream build.)
*/
public static class UpstreamCause extends Cause {
/**
* Maximum depth of transitive upstream causes we want to record.
*/
private static final int MAX_DEPTH = 10;
/**
* Maximum number of transitive upstream causes we want to record.
*/
private static final int MAX_LEAF = 25;
private String upstreamProject, upstreamUrl;
private int upstreamBuild;
/**
* @deprecated since 2009-02-28
*/
@Deprecated
private transient Cause upstreamCause;
private @Nonnull List<Cause> upstreamCauses;
/**
* @deprecated since 2009-02-28
*/
// for backward bytecode compatibility
public UpstreamCause(AbstractBuild<?,?> up) {
this((Run<?,?>)up);
}
public UpstreamCause(Run<?, ?> up) {
upstreamBuild = up.getNumber();
upstreamProject = up.getParent().getFullName();
upstreamUrl = up.getParent().getUrl();
upstreamCauses = new ArrayList<Cause>();
Set<String> traversed = new HashSet<String>();
for (Cause c : up.getCauses()) {
upstreamCauses.add(trim(c, MAX_DEPTH, traversed));
}
}
private UpstreamCause(String upstreamProject, int upstreamBuild, String upstreamUrl, @Nonnull List<Cause> upstreamCauses) {
this.upstreamProject = upstreamProject;
this.upstreamBuild = upstreamBuild;
this.upstreamUrl = upstreamUrl;
this.upstreamCauses = upstreamCauses;
}
private @Nonnull Cause trim(@Nonnull Cause c, int depth, Set<String> traversed) {
if (!(c instanceof UpstreamCause)) {
return c;
}
UpstreamCause uc = (UpstreamCause) c;
List<Cause> cs = new ArrayList<Cause>();
if (depth > 0) {
if (traversed.add(uc.upstreamUrl + uc.upstreamBuild)) {
for (Cause c2 : uc.upstreamCauses) {
cs.add(trim(c2, depth - 1, traversed));
}
}
} else if (traversed.size() < MAX_LEAF) {
cs.add(new DeeplyNestedUpstreamCause());
}
return new UpstreamCause(uc.upstreamProject, uc.upstreamBuild, uc.upstreamUrl, cs);
}
/**
* Returns true if this cause points to a build in the specified job.
*/
public boolean pointsTo(Job<?,?> j) {
return j.getFullName().equals(upstreamProject);
}
/**
* Returns true if this cause points to the specified build.
*/
public boolean pointsTo(Run<?,?> r) {
return r.getNumber()==upstreamBuild && pointsTo(r.getParent());
}
@Exported(visibility=3)
public String getUpstreamProject() {
return upstreamProject;
}
@Exported(visibility=3)
public int getUpstreamBuild() {
return upstreamBuild;
}
/**
* @since 1.505
*/
public @CheckForNull Run<?,?> getUpstreamRun() {
Job<?,?> job = Jenkins.getInstance().getItemByFullName(upstreamProject, Job.class);
return job != null ? job.getBuildByNumber(upstreamBuild) : null;
}
@Exported(visibility=3)
public String getUpstreamUrl() {
return upstreamUrl;
}
public List<Cause> getUpstreamCauses() {
return upstreamCauses;
}
@Override
public String getShortDescription() {
return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild);
}
@Override
public void print(TaskListener listener) {
print(listener, 0);
}
private void indent(TaskListener listener, int depth) {
for (int i = 0; i < depth; i++) {
listener.getLogger().print(' ');
}
}
private void print(TaskListener listener, int depth) {
indent(listener, depth);
listener.getLogger().println(
Messages.Cause_UpstreamCause_ShortDescription(
ModelHyperlinkNote.encodeTo('/' + upstreamUrl, upstreamProject),
ModelHyperlinkNote.encodeTo('/'+upstreamUrl+upstreamBuild, Integer.toString(upstreamBuild)))
);
if (upstreamCauses != null && !upstreamCauses.isEmpty()) {
indent(listener, depth);
listener.getLogger().println(Messages.Cause_UpstreamCause_CausedBy());
for (Cause cause : upstreamCauses) {
if (cause instanceof UpstreamCause) {
((UpstreamCause) cause).print(listener, depth + 1);
} else {
indent(listener, depth + 1);
cause.print(listener);
}
}
}
}
@Override public String toString() {
return upstreamUrl + upstreamBuild + upstreamCauses;
}
public static class ConverterImpl extends XStream2.PassthruConverter<UpstreamCause> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(UpstreamCause uc, UnmarshallingContext context) {
if (uc.upstreamCause != null) {
if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<Cause>();
uc.upstreamCauses.add(uc.upstreamCause);
uc.upstreamCause = null;
OldDataMonitor.report(context, "1.288");
}
}
}
public static class DeeplyNestedUpstreamCause extends Cause {
@Override public String getShortDescription() {
return "(deeply nested causes)";
}
@Override public String toString() {
return "JENKINS-14814";
}
}
}
/**
* A build is started by an user action.
*
* @deprecated 1.428
* use {@link UserIdCause}
*/
public static class UserCause extends Cause {
private String authenticationName;
public UserCause() {
this.authenticationName = Jenkins.getAuthentication().getName();
}
@Exported(visibility=3)
public String getUserName() {
User u = User.get(authenticationName, false);
return u != null ? u.getDisplayName() : authenticationName;
}
@Override
public String getShortDescription() {
return Messages.Cause_UserCause_ShortDescription(authenticationName);
}
@Override
public boolean equals(Object o) {
return o instanceof UserCause && Arrays.equals(new Object[] {authenticationName},
new Object[] {((UserCause)o).authenticationName});
}
@Override
public int hashCode() {
return 295 + (this.authenticationName != null ? this.authenticationName.hashCode() : 0);
}
}
/**
* A build is started by an user action.
*
* @since 1.427
*/
public static class UserIdCause extends Cause {
private String userId;
public UserIdCause() {
User user = User.current();
this.userId = (user == null) ? null : user.getId();
}
@Exported(visibility = 3)
public String getUserId() {
return userId;
}
@Exported(visibility = 3)
public String getUserName() {
String userName = "anonymous";
if (userId != null) {
User user = User.get(userId, false);
if (user != null)
userName = user.getDisplayName();
}
return userName;
}
@Override
public String getShortDescription() {
return Messages.Cause_UserIdCause_ShortDescription(getUserName());
}
@Override
public void print(TaskListener listener) {
listener.getLogger().println(Messages.Cause_UserIdCause_ShortDescription(
ModelHyperlinkNote.encodeTo("/user/"+getUserId(), getUserName())));
}
@Override
public boolean equals(Object o) {
return o instanceof UserIdCause && Arrays.equals(new Object[]{userId},
new Object[]{((UserIdCause) o).userId});
}
@Override
public int hashCode() {
return 295 + (this.userId != null ? this.userId.hashCode() : 0);
}
}
public static class RemoteCause extends Cause {
private String addr;
private String note;
public RemoteCause(String host, String note) {
this.addr = host;
this.note = note;
}
@Override
public String getShortDescription() {
if(note != null) {
try {
return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, Jenkins.getInstance().getMarkupFormatter().translate(note));
} catch (IOException x) {
// ignore
}
}
return Messages.Cause_RemoteCause_ShortDescription(addr);
}
@Override
public boolean equals(Object o) {
return o instanceof RemoteCause && Arrays.equals(new Object[] {addr, note},
new Object[] {((RemoteCause)o).addr, ((RemoteCause)o).note});
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + (this.addr != null ? this.addr.hashCode() : 0);
hash = 83 * hash + (this.note != null ? this.note.hashCode() : 0);
return hash;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_2099_0 |
crossvul-java_data_bad_3893_0 | /**
*
*/
package com.salesmanager.shop.store.controller.shoppingCart.facade;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.services.catalog.product.PricingService;
import com.salesmanager.core.business.services.catalog.product.ProductService;
import com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService;
import com.salesmanager.core.business.services.shoppingcart.ShoppingCartCalculationService;
import com.salesmanager.core.business.services.shoppingcart.ShoppingCartService;
import com.salesmanager.core.business.utils.ProductPriceUtils;
import com.salesmanager.core.model.catalog.product.Product;
import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute;
import com.salesmanager.core.model.catalog.product.availability.ProductAvailability;
import com.salesmanager.core.model.catalog.product.price.FinalPrice;
import com.salesmanager.core.model.customer.Customer;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.core.model.shoppingcart.ShoppingCart;
import com.salesmanager.shop.constants.Constants;
import com.salesmanager.shop.model.shoppingcart.CartModificationException;
import com.salesmanager.shop.model.shoppingcart.PersistableShoppingCartItem;
import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartAttribute;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartData;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartItem;
import com.salesmanager.shop.populator.shoppingCart.ReadableShoppingCartPopulator;
import com.salesmanager.shop.populator.shoppingCart.ShoppingCartDataPopulator;
import com.salesmanager.shop.store.api.exception.ResourceNotFoundException;
import com.salesmanager.shop.utils.DateUtil;
import com.salesmanager.shop.utils.ImageFilePath;
/**
* @author Umesh Awasthi
* @version 1.0
* @since 1.0
*/
@Service( value = "shoppingCartFacade" )
public class ShoppingCartFacadeImpl
implements ShoppingCartFacade
{
private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartFacadeImpl.class);
@Inject
private ShoppingCartService shoppingCartService;
@Inject
ShoppingCartCalculationService shoppingCartCalculationService;
@Inject
private ProductPriceUtils productPriceUtils;
@Inject
private ProductService productService;
@Inject
private PricingService pricingService;
@Inject
private ProductAttributeService productAttributeService;
@Inject
@Qualifier("img")
private ImageFilePath imageUtils;
public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception {
ShoppingCart cart = shoppingCartService.getById(id, store);
if(cart!=null) {
shoppingCartService.deleteCart(cart);
}
}
@Override
public void deleteShoppingCart(final String code, final MerchantStore store) throws Exception {
ShoppingCart cart = shoppingCartService.getByCode(code, store);
if(cart!=null) {
shoppingCartService.deleteCart(cart);
}
}
@Override
public ShoppingCartData addItemsToShoppingCart( final ShoppingCartData shoppingCartData,
final ShoppingCartItem item, final MerchantStore store, final Language language,final Customer customer )
throws Exception
{
ShoppingCart cartModel = null;
/**
* Sometimes a user logs in and a shopping cart is present in db (shoppingCartData
* but ui has no cookie with shopping cart code so the cart code will have
* to be added to the item in order to process add to cart normally
*/
if(shoppingCartData != null && StringUtils.isBlank(item.getCode())) {
item.setCode(shoppingCartData.getCode());
}
if ( !StringUtils.isBlank( item.getCode() ) )
{
// get it from the db
cartModel = getShoppingCartModel( item.getCode(), store );
if ( cartModel == null )
{
cartModel = createCartModel( shoppingCartData.getCode(), store,customer );
}
}
if ( cartModel == null )
{
final String shoppingCartCode =
StringUtils.isNotBlank( shoppingCartData.getCode() ) ? shoppingCartData.getCode() : null;
cartModel = createCartModel( shoppingCartCode, store,customer );
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem =
createCartItem( cartModel, item, store );
boolean duplicateFound = false;
if(CollectionUtils.isEmpty(item.getShoppingCartAttributes())) {//increment quantity
//get duplicate item from the cart
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartModelItems = cartModel.getLineItems();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) {
if(cartItem.getProduct().getId().longValue()==shoppingCartItem.getProduct().getId().longValue()) {
if(CollectionUtils.isEmpty(cartItem.getAttributes())) {
if(!duplicateFound) {
if(!shoppingCartItem.isProductVirtual()) {
cartItem.setQuantity(cartItem.getQuantity() + shoppingCartItem.getQuantity());
}
duplicateFound = true;
break;
}
}
}
}
}
if(!duplicateFound) {
//shoppingCartItem.getAttributes().stream().forEach(a -> {a.setProductAttributeId(productAttributeId);});
cartModel.getLineItems().add( shoppingCartItem );
}
/** Update cart in database with line items **/
shoppingCartService.saveOrUpdate( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
shoppingCartCalculationService.calculate( cartModel, store, language );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem( final ShoppingCart cartModel,
final ShoppingCartItem shoppingCartItem,
final MerchantStore store )
throws Exception
{
Product product = productService.getById( shoppingCartItem.getProductId() );
if ( product == null )
{
throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not exist" );
}
if ( product.getMerchantStore().getId().intValue() != store.getId().intValue() )
{
throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not belong to merchant "
+ store.getId() );
}
/**
* Check if product quantity is 0
* Check if product is available
* Check if date available <= now
*/
Set<ProductAvailability> availabilities = product.getAvailabilities();
if(availabilities == null) {
throw new Exception( "Item with id " + product.getId() + " is not properly configured" );
}
for(ProductAvailability availability : availabilities) {
if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() ==0) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
}
if(!product.isAvailable()) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem item =
shoppingCartService.populateShoppingCartItem( product );
item.setQuantity( shoppingCartItem.getQuantity() );
item.setShoppingCart( cartModel );
// attributes
List<ShoppingCartAttribute> cartAttributes = shoppingCartItem.getShoppingCartAttributes();
if ( !CollectionUtils.isEmpty( cartAttributes ) )
{
for ( ShoppingCartAttribute attribute : cartAttributes )
{
ProductAttribute productAttribute = productAttributeService.getById( attribute.getAttributeId() );
if ( productAttribute != null
&& productAttribute.getProduct().getId().longValue() == product.getId().longValue() )
{
com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem =
new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( item,
productAttribute );
item.addAttributes( attributeItem );
}
}
}
return item;
}
//used for api
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(ShoppingCart cartModel,
PersistableShoppingCartItem shoppingCartItem, MerchantStore store) throws Exception {
Product product = productService.getById(shoppingCartItem.getProduct());
if (product == null) {
throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not exist");
}
if (product.getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not belong to merchant "
+ store.getId());
}
/**
* Check if product quantity is 0
* Check if product is available
* Check if date available <= now
*/
Set<ProductAvailability> availabilities = product.getAvailabilities();
if(availabilities == null) {
throw new Exception( "Item with id " + product.getId() + " is not properly configured" );
}
for(ProductAvailability availability : availabilities) {
if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() ==0) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
}
if(!product.isAvailable()) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService
.populateShoppingCartItem(product);
item.setQuantity(shoppingCartItem.getQuantity());
item.setShoppingCart(cartModel);
//set attributes
List<com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute> attributes = shoppingCartItem.getAttributes();
if (!CollectionUtils.isEmpty(attributes)) {
for(com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) {
ProductAttribute productAttribute = productAttributeService.getById(attribute.getId());
if (productAttribute != null
&& productAttribute.getProduct().getId().longValue() == product.getId().longValue()) {
com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem(
item, productAttribute);
item.addAttributes(attributeItem);
}
}
}
return item;
}
@Override
public ShoppingCart createCartModel( final String shoppingCartCode, final MerchantStore store,final Customer customer )
throws Exception
{
final Long CustomerId = customer != null ? customer.getId() : null;
ShoppingCart cartModel = new ShoppingCart();
if ( StringUtils.isNotBlank( shoppingCartCode ) )
{
cartModel.setShoppingCartCode( shoppingCartCode );
}
else
{
cartModel.setShoppingCartCode( uniqueShoppingCartCode() );
}
cartModel.setMerchantStore( store );
if ( CustomerId != null )
{
cartModel.setCustomerId( CustomerId );
}
shoppingCartService.create( cartModel );
return cartModel;
}
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem getEntryToUpdate( final long entryId,
final ShoppingCart cartModel )
{
if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) )
{
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() )
{
if ( shoppingCartItem.getId().longValue() == entryId )
{
LOG.info( "Found line item for given entry id: " + entryId );
return shoppingCartItem;
}
}
}
LOG.info( "Unable to find any entry for given Id: " + entryId );
return null;
}
private Object getKeyValue( final String key )
{
ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return reqAttr.getRequest().getAttribute( key );
}
@Override
public ShoppingCartData getShoppingCartData( final Customer customer, final MerchantStore store,
final String shoppingCartId, Language language)
throws Exception
{
ShoppingCart cart = null;
try
{
if ( customer != null )
{
LOG.info( "Reteriving customer shopping cart..." );
cart = shoppingCartService.getShoppingCart( customer );
}
else
{
if ( StringUtils.isNotBlank( shoppingCartId ) && cart == null )
{
cart = shoppingCartService.getByCode( shoppingCartId, store );
}
}
}
catch ( ServiceException ex )
{
LOG.error( "Error while retriving cart from customer", ex );
}
catch( NoResultException nre) {
//nothing
}
if ( cart == null )
{
return null;
}
LOG.info( "Cart model found." );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
//Language language = (Language) getKeyValue( Constants.LANGUAGE );
MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE );
ShoppingCartData shoppingCartData = shoppingCartDataPopulator.populate( cart, merchantStore, language );
/* List<ShoppingCartItem> unavailables = new ArrayList<ShoppingCartItem>();
List<ShoppingCartItem> availables = new ArrayList<ShoppingCartItem>();
//Take out items no more available
List<ShoppingCartItem> items = shoppingCartData.getShoppingCartItems();
for(ShoppingCartItem item : items) {
String code = item.getProductCode();
Product p =productService.getByCode(code, language);
if(!p.isAvailable()) {
unavailables.add(item);
} else {
availables.add(item);
}
}
shoppingCartData.setShoppingCartItems(availables);
shoppingCartData.setUnavailables(unavailables);*/
return shoppingCartData;
}
//@Override
public ShoppingCartData getShoppingCartData( final ShoppingCart shoppingCartModel, Language language)
throws Exception
{
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
//Language language = (Language) getKeyValue( Constants.LANGUAGE );
MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE );
return shoppingCartDataPopulator.populate( shoppingCartModel, merchantStore, language );
}
@Override
public ShoppingCartData removeCartItem( final Long itemID, final String cartId ,final MerchantStore store,final Language language )
throws Exception
{
if ( StringUtils.isNotBlank( cartId ) )
{
ShoppingCart cartModel = getCartModel( cartId,store );
if ( cartModel != null )
{
if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) )
{
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> shoppingCartItemSet =
new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() )
{
if(shoppingCartItem.getId().longValue() == itemID.longValue() )
{
shoppingCartService.deleteShoppingCartItem(itemID);
} else {
shoppingCartItemSet.add(shoppingCartItem);
}
}
cartModel.setLineItems(shoppingCartItemSet);
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
}
}
return null;
}
@Override
public ShoppingCartData updateCartItem( final Long itemID, final String cartId, final long newQuantity,final MerchantStore store, final Language language )
throws Exception
{
if ( newQuantity < 1 )
{
throw new CartModificationException( "Quantity must not be less than one" );
}
if ( StringUtils.isNotBlank( cartId ) )
{
ShoppingCart cartModel = getCartModel( cartId,store );
if ( cartModel != null )
{
com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate =
getEntryToUpdate( itemID.longValue(), cartModel );
if ( entryToUpdate == null )
{
throw new CartModificationException( "Unknown entry number." );
}
entryToUpdate.getProduct();
LOG.info( "Updating cart entry quantity to" + newQuantity );
entryToUpdate.setQuantity( (int) newQuantity );
List<ProductAttribute> productAttributes = new ArrayList<ProductAttribute>();
productAttributes.addAll( entryToUpdate.getProduct().getAttributes() );
final FinalPrice finalPrice =
productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes );
entryToUpdate.setItemPrice( finalPrice.getFinalPrice() );
shoppingCartService.saveOrUpdate( cartModel );
LOG.info( "Cart entry updated with desired quantity" );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public ShoppingCartData updateCartItems( final List<ShoppingCartItem> shoppingCartItems, final MerchantStore store, final Language language )
throws Exception
{
Validate.notEmpty(shoppingCartItems,"shoppingCartItems null or empty");
ShoppingCart cartModel = null;
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for(ShoppingCartItem item : shoppingCartItems) {
if(item.getQuantity()<1) {
throw new CartModificationException( "Quantity must not be less than one" );
}
if(cartModel==null) {
cartModel = getCartModel( item.getCode(), store );
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate =
getEntryToUpdate( item.getId(), cartModel );
if ( entryToUpdate == null ) {
throw new CartModificationException( "Unknown entry number." );
}
entryToUpdate.getProduct();
LOG.info( "Updating cart entry quantity to" + item.getQuantity() );
entryToUpdate.setQuantity( (int) item.getQuantity() );
List<ProductAttribute> productAttributes = new ArrayList<ProductAttribute>();
productAttributes.addAll( entryToUpdate.getProduct().getAttributes() );
final FinalPrice finalPrice =
productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes );
entryToUpdate.setItemPrice( finalPrice.getFinalPrice() );
cartItems.add(entryToUpdate);
}
cartModel.setLineItems(cartItems);
shoppingCartService.saveOrUpdate( cartModel );
LOG.info( "Cart entry updated with desired quantity" );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
private ShoppingCart getCartModel( final String cartId,final MerchantStore store )
{
if ( StringUtils.isNotBlank( cartId ) )
{
try
{
return shoppingCartService.getByCode( cartId, store );
}
catch ( ServiceException e )
{
LOG.error( "unable to find any cart asscoiated with this Id: " + cartId );
LOG.error( "error while fetching cart model...", e );
return null;
}
catch( NoResultException nre) {
//nothing
}
}
return null;
}
@Override
public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language language) {
try {
ShoppingCart cartModel = shoppingCartService.getByCode( code, store );
if(cartModel!=null) {
ShoppingCartData cart = getShoppingCartData(cartModel, language);
return cart;
}
} catch( NoResultException nre) {
//nothing
} catch(Exception e) {
LOG.error("Cannot retrieve cart code " + code,e);
}
return null;
}
@Override
public ShoppingCart getShoppingCartModel(String shoppingCartCode,
MerchantStore store) throws Exception {
return shoppingCartService.getByCode( shoppingCartCode, store );
}
@Override
public ShoppingCart getShoppingCartModel(Customer customer,
MerchantStore store) throws Exception {
return shoppingCartService.getByCustomer(customer);
}
@Override
public void saveOrUpdateShoppingCart(ShoppingCart cart) throws Exception {
shoppingCartService.saveOrUpdate(cart);
}
@Override
public ReadableShoppingCart getCart(Customer customer, MerchantStore store, Language language) throws Exception {
Validate.notNull(customer,"Customer cannot be null");
Validate.notNull(customer.getId(),"Customer.id cannot be null or empty");
//Check if customer has an existing shopping cart
ShoppingCart cartModel = shoppingCartService.getByCustomer(customer);
if(cartModel == null) {
return null;
}
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
@Override
public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(item,"PersistableShoppingCartItem cannot be null");
//if cart does not exist create a new one
ShoppingCart cartModel = new ShoppingCart();
cartModel.setMerchantStore(store);
cartModel.setShoppingCartCode(uniqueShoppingCartCode());
return readableShoppingCart(cartModel,item,store,language);
}
@SuppressWarnings("unchecked")
@Override
public void removeShoppingCartItem(String cartCode, Long productId,
MerchantStore merchant, Language language) throws Exception {
Validate.notNull(cartCode, "Shopping cart code must not be null");
Validate.notNull(productId, "product id must not be null");
Validate.notNull(merchant, "MerchantStore must not be null");
//get cart
ShoppingCart cart = getCartModel(cartCode, merchant);
if(cart == null) {
throw new ResourceNotFoundException("Cart code [ " + cartCode + " ] not found");
}
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemToDelete = null;
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cart.getLineItems() )
{
if ( shoppingCartItem.getProduct().getId().longValue() == productId.longValue() )
{
//get cart item
itemToDelete =
getEntryToUpdate( shoppingCartItem.getId(), cart );
//break;
} else {
items.add(shoppingCartItem);
}
}
//delete item
if(itemToDelete!=null) {
shoppingCartService.deleteShoppingCartItem(itemToDelete.getId());
}
//remaining items
if(items.size()>0) {
cart.setLineItems(items);
} else {
cart.getLineItems().clear();
}
//if(items.size()>0) {
shoppingCartService.saveOrUpdate(cart);//update cart with remaining items
//ReadableShoppingCart readableShoppingCart = this.getByCode(cartCode, merchant, language);
//}
}
private ReadableShoppingCart readableShoppingCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store);
//need to check if the item is already in the cart
boolean duplicateFound = false;
//only if item has no attributes
if(CollectionUtils.isEmpty(item.getAttributes())) {//increment quantity
//get duplicate item from the cart
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartModelItems = cartModel.getLineItems();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) {
if(cartItem.getProduct().getId().longValue()==item.getProduct().longValue()) {
if(CollectionUtils.isEmpty(cartItem.getAttributes())) {
if(!duplicateFound) {
if(!itemModel.isProductVirtual()) {
cartItem.setQuantity(cartItem.getQuantity() + item.getQuantity());
}
duplicateFound = true;
break;
}
}
}
}
}
if(!duplicateFound) {
cartModel.getLineItems().add( itemModel );
}
saveShoppingCart( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
private ReadableShoppingCart modifyCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store);
boolean itemModified = false;
//check if existing product
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cartModel.getLineItems();
//com.salesmanager.core.model.shoppingcart.ShoppingCartItem affectedItem = null;
if(!CollectionUtils.isEmpty(items)) {
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> newItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> removeItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem anItem : items) {//take care of existing product
if(itemModel.getProduct().getId().longValue() == anItem.getProduct().getId()) {
if(item.getQuantity()==0) {//left aside item to be removed
//don't add it to new list of item
removeItems.add(anItem);
} else {
//new quantity
anItem.setQuantity(item.getQuantity());
newItems.add(anItem);
}
itemModified = true;
} else {
newItems.add(anItem);
}
}
if(!removeItems.isEmpty()) {
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem emptyItem : removeItems) {
shoppingCartService.deleteShoppingCartItem(emptyItem.getId());
}
}
if(!itemModified) {
newItems.add(itemModel);
}
if(newItems.isEmpty()) {
newItems = null;
}
cartModel.setLineItems(newItems);
} else {
//new item
if(item.getQuantity() > 0) {
cartModel.getLineItems().add( itemModel );
}
}
//if cart items are null just return cart with no items
saveShoppingCart( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
if(cartModel==null) {
return null;
}
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
@Override
public ReadableShoppingCart addToCart(Customer customer, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(customer,"Customer cannot be null");
Validate.notNull(customer.getId(),"Customer.id cannot be null or empty");
//Check if customer has an existing shopping cart
ShoppingCart cartModel = shoppingCartService.getByCustomer(customer);
//if cart does not exist create a new one
if(cartModel==null) {
cartModel = new ShoppingCart();
cartModel.setCustomerId(customer.getId());
cartModel.setMerchantStore(store);
cartModel.setShoppingCartCode(uniqueShoppingCartCode());
}
return readableShoppingCart(cartModel,item,store,language);
}
@Override
public ReadableShoppingCart modifyCart(String cartCode, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(cartCode,"PString cart code cannot be null");
Validate.notNull(item,"PersistableShoppingCartItem cannot be null");
ShoppingCart cartModel = this.getCartModel(cartCode, store);
return modifyCart(cartModel,item, store, language);
}
private void saveShoppingCart(ShoppingCart shoppingCart) throws Exception {
shoppingCartService.save(shoppingCart);
}
private String uniqueShoppingCartCode() {
return UUID.randomUUID().toString().replaceAll( "-", "" );
}
@Override
public ReadableShoppingCart getById(Long shoppingCartId, MerchantStore store, Language language) throws Exception {
ShoppingCart cart = shoppingCartService.getById(shoppingCartId);
ReadableShoppingCart readableCart = null;
if(cart != null) {
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
readableShoppingCart.populate(cart, readableCart, store, language);
}
return readableCart;
}
@Override
public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Exception {
return shoppingCartService.getById(id);
}
@Override
public ReadableShoppingCart getByCode(String code, MerchantStore store, Language language) throws Exception {
ShoppingCart cart = shoppingCartService.getByCode(code, store);
ReadableShoppingCart readableCart = null;
if(cart != null) {
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
readableCart = readableShoppingCart.populate(cart, null, store, language);
}
return readableCart;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_3893_0 |
crossvul-java_data_good_24_2 | package org.jolokia.http;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.io.*;
import java.net.SocketException;
import java.util.*;
import javax.management.JMException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jolokia.backend.TestDetector;
import org.jolokia.config.ConfigKey;
import org.jolokia.discovery.JolokiaDiscovery;
import org.jolokia.restrictor.*;
import org.jolokia.test.util.HttpTestUtil;
import org.jolokia.util.LogHandler;
import org.jolokia.util.NetworkUtil;
import org.jolokia.util.QuietLogHandler;
import org.json.simple.JSONObject;
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 30.08.11
*/
public class AgentServletTest {
private ServletContext context;
private ServletConfig config;
private HttpServletRequest request;
private HttpServletResponse response;
private AgentServlet servlet;
@Test
public void simpleInit() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(null, null,"No access restrictor found", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithAcessRestriction() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "classpath:/access-sample1.xml"},
null,
"Using access restrictor.*access-sample1.xml", null);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void initWithInvalidPolicyFile() throws ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.POLICY_LOCATION.getKeyValue(), "file:///blablub.xml"},
null,
"Error.*blablub.xml.*Denying", FileNotFoundException.class);
replay(config, context);
servlet.init(config);
servlet.destroy();
}
@Test
public void configWithOverWrite() throws ServletException {
servlet = new AgentServlet();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
initConfigMocks(new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/jmx4perl",ConfigKey.MAX_DEPTH.getKeyValue(),"10"},
new String[] {ConfigKey.AGENT_CONTEXT.getKeyValue(),"/j0l0k14",ConfigKey.MAX_OBJECTS.getKeyValue(),"20",
ConfigKey.CALLBACK.getKeyValue(),"callback is a request option, must be empty here"},
null,null);
replay(config, context,request,response);
servlet.init(config);
servlet.destroy();
org.jolokia.config.Configuration cfg = servlet.initConfig(config);
assertEquals(cfg.get(ConfigKey.AGENT_CONTEXT), "/j0l0k14");
assertEquals(cfg.get(ConfigKey.MAX_DEPTH), "10");
assertEquals(cfg.get(ConfigKey.MAX_OBJECTS), "20");
assertNull(cfg.get(ConfigKey.CALLBACK));
assertNull(cfg.get(ConfigKey.DETECTOR_OPTIONS));
}
@Test
public void initWithCustomAccessRestrictor() throws ServletException {
prepareStandardInitialisation();
servlet.destroy();
}
@Test
public void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andStubReturn(context);
expect(config.getServletName()).andStubReturn("jolokia");
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
}
@Test
public void initWithAgentDiscoveryAndGivenUrl() throws ServletException, IOException, InterruptedException {
checkMulticastAvailable();
String url = "http://localhost:8080/jolokia";
prepareStandardInitialisation(ConfigKey.DISCOVERY_AGENT_URL.getKeyValue(), url);
// Wait listening thread to warm up
Thread.sleep(1000);
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test", new QuietLogHandler());
List<JSONObject> in = discovery.lookupAgentsWithTimeout(500);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
return;
}
}
fail("No agent found");
} finally {
servlet.destroy();
}
}
@Test
public void initWithAgentDiscoveryAndUrlLookup() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
JolokiaDiscovery discovery = new JolokiaDiscovery("test", new QuietLogHandler());
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
// At least one doesnt have an URL (remove this part if a way could be found for getting
// to the URL
for (JSONObject json : in) {
if (json.get("url") == null) {
return;
}
}
fail("Every message has an URL");
} finally {
servlet.destroy();
}
}
private void checkMulticastAvailable() throws SocketException {
if (!NetworkUtil.isMulticastSupported()) {
throw new SkipException("No multicast interface found, skipping test ");
}
}
@Test
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
String url = "http://10.9.11.1:9876/jolokia";
ByteArrayOutputStream sw = initRequestResponseMocks(
getDiscoveryRequestSetup(url),
getStandardResponseSetup());
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",new QuietLogHandler());
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
}
public static class CustomLogHandler implements LogHandler {
private static int infoCount = 0;
public CustomLogHandler() {
infoCount = 0;
}
public void debug(String message) {
}
public void info(String message) {
infoCount++;
}
public void error(String message, Throwable t) {
}
}
@Test
public void simpleGet() throws ServletException, IOException {
prepareStandardInitialisation();
ByteArrayOutputStream sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
expect(request.getAttribute("subject")).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void simpleGetWithWrongMimeType() throws ServletException, IOException {
checkMimeTypes("text/html", "text/plain");
}
@Test
public void simpleGetWithTextPlainMimeType() throws ServletException, IOException {
checkMimeTypes("text/plain", "text/plain");
}
@Test
public void simpleGetWithApplicationJsonMimeType() throws ServletException, IOException {
checkMimeTypes("application/json", "application/json");
}
private void checkMimeTypes(String given, final String expected) throws ServletException, IOException {
prepareStandardInitialisation();
initRequestResponseMocks(
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
// The default content type
response.setContentType(expected);
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(given);
replay(request, response);
servlet.doGet(request, response);
verifyMocks();
servlet.destroy();
}
@Test
public void simpleGetWithNoReverseDnsLookupFalse() throws ServletException, IOException {
checkNoReverseDns(false,"127.0.0.1");
}
@Test
public void simpleGetWithNoReverseDnsLookupTrue() throws ServletException, IOException {
checkNoReverseDns(true,"localhost","127.0.0.1");
}
private void checkNoReverseDns(boolean enabled, String ... expectedHosts) throws ServletException, IOException {
prepareStandardInitialisation(
(Restrictor) null,
ConfigKey.RESTRICTOR_CLASS.getKeyValue(),NoDnsLookupRestrictorChecker.class.getName(),
ConfigKey.ALLOW_DNS_REVERSE_LOOKUP.getKeyValue(),Boolean.toString(enabled));
NoDnsLookupRestrictorChecker.expectedHosts = expectedHosts;
ByteArrayOutputStream sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
expect(request.getAttribute("subject")).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertFalse(sw.toString().contains("error"));
servlet.destroy();
}
// Check whether restrictor is called with the proper args
public static class NoDnsLookupRestrictorChecker extends AbstractConstantRestrictor {
static String[] expectedHosts;
public NoDnsLookupRestrictorChecker() {
super(true);
}
@Override
public boolean isRemoteAccessAllowed(String... pHostOrAddress) {
if (expectedHosts.length != pHostOrAddress.length) {
return false;
}
for (int i = 0; i < expectedHosts.length; i++) {
if (!expectedHosts[i].equals(pHostOrAddress[i])) {
return false;
}
}
return true;
}
}
@Test
public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
prepareStandardInitialisation();
ByteArrayOutputStream sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
setupAgentDetailsInitExpectations();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
Vector params = new Vector();
params.add("debug");
expect(request.getParameterNames()).andReturn(params.elements());
expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request,response);
servlet.doGet(request,response);
servlet.destroy();
}
@Test
public void simplePost() throws ServletException, IOException {
prepareStandardInitialisation();
ByteArrayOutputStream responseWriter = initRequestResponseMocks();
expect(request.getCharacterEncoding()).andReturn("utf-8");
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
expect(request.getAttribute("subject")).andReturn(null);
preparePostRequest(HttpTestUtil.HEAP_MEMORY_POST_REQUEST);
replay(request, response);
servlet.doPost(request, response);
assertTrue(responseWriter.toString().contains("used"));
servlet.destroy();
}
@Test
public void unknownMethodWhenSettingContentType() throws ServletException, IOException {
prepareStandardInitialisation();
ByteArrayOutputStream sw = initRequestResponseMocks(
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
expectLastCall().andThrow(new NoSuchMethodError());
response.setContentType("text/plain; charset=utf-8");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
expect(request.getAttribute("subject")).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@Test
public void corsPreflightCheck() throws ServletException, IOException {
checkCorsOriginPreflight("http://bla.com", "http://bla.com");
}
@Test
public void corsPreflightCheckWithNullOrigin() throws ServletException, IOException {
checkCorsOriginPreflight("null", "*");
}
private void checkCorsOriginPreflight(String in, String out) throws ServletException, IOException {
prepareStandardInitialisation();
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getHeader("Access-Control-Request-Headers")).andReturn(null);
response.setHeader(eq("Access-Control-Max-Age"), (String) anyObject());
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials", "true");
replay(request, response);
servlet.doOptions(request, response);
servlet.destroy();
}
@Test
public void corsHeaderGetCheck() throws ServletException, IOException {
checkCorsGetOrigin("http://bla.com","http://bla.com");
}
@Test
public void corsHeaderGetCheckWithNullOrigin() throws ServletException, IOException {
checkCorsGetOrigin("null","*");
}
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
ByteArrayOutputStream sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
expect(request.getHeader("Origin")).andStubReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/").times(2);
expect(request.getRequestURL()).andReturn(new StringBuffer("http://localhost/jolokia"));
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn(null);
expect(request.getParameterMap()).andReturn(null);
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
expect(request.getAttribute("subject")).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
}
private void setNoCacheHeaders(HttpServletResponse pResp) {
pResp.setHeader("Cache-Control", "no-cache");
pResp.setHeader("Pragma","no-cache");
pResp.setDateHeader(eq("Date"),anyLong());
pResp.setDateHeader(eq("Expires"),anyLong());
}
@Test
public void withCallback() throws IOException, ServletException {
prepareStandardInitialisation();
ByteArrayOutputStream sw = initRequestResponseMocks(
"myCallback",
getStandardRequestSetup(),
new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
response.setContentType("text/javascript");
response.setStatus(200);
}
});
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().matches("^myCallback\\(.*\\);$"));
servlet.destroy();
}
@Test
public void withInvalidCallback() throws IOException, ServletException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(null, null,"Error 400", IllegalArgumentException.class);
replay(config, context);
servlet.init(config);
ByteArrayOutputStream sw = initRequestResponseMocks(
"doSomethingEvil(); myCallback",
getStandardRequestSetup(),
getStandardResponseSetup());
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
String resp = sw.toString();
assertTrue(resp.contains("error_type"));
assertTrue(resp.contains("IllegalArgumentException"));
assertTrue(resp.matches(".*status.*400.*"));
servlet.destroy();
}
@Test
public void withException() throws ServletException, IOException {
servlet = new AgentServlet(new AllowAllRestrictor());
initConfigMocks(null, null,"Error 500", IllegalStateException.class);
replay(config, context);
servlet.init(config);
ByteArrayOutputStream sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andThrow(new IllegalStateException());
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
String resp = sw.toString();
assertTrue(resp.contains("error_type"));
assertTrue(resp.contains("IllegalStateException"));
assertTrue(resp.matches(".*status.*500.*"));
servlet.destroy();
verify(config, context, request, response);
}
@Test
public void debug() throws IOException, ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null);
context.log(find("URI:"));
context.log(find("Path-Info:"));
context.log(find("Request:"));
context.log(find("time:"));
context.log(find("Response:"));
context.log(find("TestDetector"),isA(RuntimeException.class));
expectLastCall().asStub();
replay(config, context);
servlet.init(config);
ByteArrayOutputStream sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
expect(request.getAttribute("subject")).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
}
@BeforeMethod
void resetTestDetector() {
TestDetector.reset();
}
//@AfterMethod
public void verifyMocks() {
verify(config, context, request, response);
}
// ============================================================================================
private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) {
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];
params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();
params[params.length - 1] = "true";
HttpTestUtil.prepareServletConfigMock(config,params);
HttpTestUtil.prepareServletContextMock(context, pContextParams);
expect(config.getServletContext()).andStubReturn(context);
expect(config.getServletName()).andStubReturn("jolokia");
if (pExceptionClass != null) {
context.log(find(pLogRegexp),isA(pExceptionClass));
} else {
if (pLogRegexp != null) {
context.log(find(pLogRegexp));
} else {
context.log((String) anyObject());
}
}
context.log((String) anyObject());
expectLastCall().asStub();
context.log(find("TestDetector"),isA(RuntimeException.class));
context.log((String) anyObject(),isA(JMException.class));
expectLastCall().anyTimes();
}
private ByteArrayOutputStream initRequestResponseMocks() throws IOException {
return initRequestResponseMocks(
getStandardRequestSetup(),
getStandardResponseSetup());
}
private ByteArrayOutputStream initRequestResponseMocks(Runnable requestSetup,Runnable responseSetup) throws IOException {
return initRequestResponseMocks(null,requestSetup,responseSetup);
}
private ByteArrayOutputStream initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException {
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
setNoCacheHeaders(response);
expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback).anyTimes();
requestSetup.run();
responseSetup.run();
class MyServletOutputStream extends ServletOutputStream {
ByteArrayOutputStream baos;
public void write(int b) throws IOException {
baos.write(b);
}
public void setBaos(ByteArrayOutputStream baos){
this.baos = baos;
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MyServletOutputStream sos = new MyServletOutputStream();
sos.setBaos(baos);
expect(response.getOutputStream()).andReturn(sos);
return baos;
}
private void preparePostRequest(String pReq) throws IOException {
ServletInputStream is = HttpTestUtil.createServletInputStream(pReq);
expect(request.getInputStream()).andReturn(is);
}
private void prepareStandardInitialisation(Restrictor restrictor, String ... params) throws ServletException {
servlet = new AgentServlet(restrictor);
initConfigMocks(params.length > 0 ? params : null, null,"custom access", null);
replay(config, context);
servlet.init(config);
}
private void prepareStandardInitialisation(String ... params) throws ServletException {
prepareStandardInitialisation(new AllowAllRestrictor(),params);
}
private Runnable getStandardResponseSetup() {
return new Runnable() {
public void run() {
response.setCharacterEncoding("utf-8");
// The default content type
response.setContentType("text/plain");
response.setStatus(200);
}
};
}
private Runnable getStandardRequestSetup() {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andStubReturn("localhost");
expect(request.getRemoteAddr()).andStubReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
setupAgentDetailsInitExpectations();
expect(request.getParameterMap()).andReturn(null);
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
}
};
}
private void setupAgentDetailsInitExpectations() {
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getRequestURL()).andReturn(new StringBuffer("http://localhost/jolokia"));
expect(request.getContextPath()).andReturn("/jolokia/");
expect(request.getAuthType()).andReturn(null);
}
private Runnable getDiscoveryRequestSetup(final String url) {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain").anyTimes();
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
}
};
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_24_2 |
crossvul-java_data_good_2083_1 | /*
* Copyright 2002-2014 the original author or authors.
*
* 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 org.springframework.web.servlet.tags.form;
import java.util.Collections;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.mockito.BDDMockito.*;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
* @author Scott Andrews
* @author Jeremy Grelle
* @author Rossen Stoyanchev
*/
public class FormTagTests extends AbstractHtmlElementTagTests {
private static final String REQUEST_URI = "/my/form";
private static final String QUERY_STRING = "foo=bar";
private FormTag tag;
private MockHttpServletRequest request;
@Override
@SuppressWarnings("serial")
protected void onSetUp() {
this.tag = new FormTag() {
@Override
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
@Override
protected void extendRequest(MockHttpServletRequest request) {
request.setRequestURI(REQUEST_URI);
request.setQueryString(QUERY_STRING);
this.request = request;
}
public void testWriteForm() throws Exception {
String commandName = "myCommand";
String name = "formName";
String action = "/form.html";
String method = "POST";
String target = "myTarget";
String enctype = "my/enctype";
String acceptCharset = "iso-8859-1";
String onsubmit = "onsubmit";
String onreset = "onreset";
String autocomplete = "off";
String cssClass = "myClass";
String cssStyle = "myStyle";
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
this.tag.setName(name);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setCommandName(commandName);
this.tag.setAction(action);
this.tag.setMethod(method);
this.tag.setTarget(target);
this.tag.setEnctype(enctype);
this.tag.setAcceptCharset(acceptCharset);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
this.tag.setAutocomplete(autocomplete);
this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "class", cssClass);
assertContainsAttribute(output, "style", cssStyle);
assertContainsAttribute(output, "action", action);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "target", target);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "accept-charset", acceptCharset);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertContainsAttribute(output, "autocomplete", autocomplete);
assertContainsAttribute(output, "id", commandName);
assertContainsAttribute(output, "name", name);
assertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1);
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testWithActionFromRequest() throws Exception {
String commandName = "myCommand";
String enctype = "my/enctype";
String method = "POST";
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "action", REQUEST_URI + "?" + QUERY_STRING);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertAttributeNotPresent(output, "name");
}
public void testPrependServletPath() throws Exception {
this.request.setContextPath("/myApp");
this.request.setServletPath("/main");
this.request.setPathInfo("/index.html");
String commandName = "myCommand";
String action = "/form.html";
String enctype = "my/enctype";
String method = "POST";
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setServletRelativeAction(action);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "action", "/myApp/main/form.html");
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertAttributeNotPresent(output, "name");
}
public void testWithNullResolvedCommand() throws Exception {
try {
tag.setCommandName(null);
tag.doStartTag();
fail("Must not be able to have a command name that resolves to null");
}
catch (IllegalArgumentException ex) {
// expected
}
}
/*
* See http://opensource.atlassian.com/projects/spring/browse/SPR-2645
*/
public void testXSSScriptingExploitWhenActionIsResolvedFromQueryString() throws Exception {
String xssQueryString = QUERY_STRING + "&stuff=\"><script>alert('XSS!')</script>";
request.setQueryString(xssQueryString);
tag.doStartTag();
assertEquals("<form id=\"command\" action=\"/my/form?foo=bar&stuff="><script>alert('XSS!')</script>\" method=\"post\">",
getOutput());
}
public void testGet() throws Exception {
this.tag.setMethod("get");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "get");
assertEquals("", inputOutput);
}
public void testPost() throws Exception {
this.tag.setMethod("post");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertEquals("", inputOutput);
}
public void testPut() throws Exception {
this.tag.setMethod("put");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "_method");
assertContainsAttribute(inputOutput, "value", "put");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testDelete() throws Exception {
this.tag.setMethod("delete");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "_method");
assertContainsAttribute(inputOutput, "value", "delete");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testCustomMethodParameter() throws Exception {
this.tag.setMethod("put");
this.tag.setMethodParam("methodParameter");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
String inputOutput = getInputTag(output);
assertContainsAttribute(formOutput, "method", "post");
assertContainsAttribute(inputOutput, "name", "methodParameter");
assertContainsAttribute(inputOutput, "value", "put");
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testClearAttributesOnFinally() throws Exception {
this.tag.setModelAttribute("model");
getPageContext().setAttribute("model", "foo bar");
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
this.tag.doStartTag();
assertNotNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
this.tag.doFinally();
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testRequestDataValueProcessorHooks() throws Exception {
String action = "/my/form?foo=bar";
RequestDataValueProcessor processor = getMockRequestDataValueProcessor();
given(processor.processAction(this.request, action, "post")).willReturn(action);
given(processor.getExtraHiddenFields(this.request)).willReturn(Collections.singletonMap("key", "value"));
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
assertEquals("<div>\n<input type=\"hidden\" name=\"key\" value=\"value\" />\n</div>", getInputTag(output));
assertFormTagOpened(output);
assertFormTagClosed(output);
}
public void testDefaultActionEncoded() throws Exception {
this.request.setRequestURI("/a b c");
request.setQueryString("");
this.tag.doStartTag();
this.tag.doEndTag();
this.tag.doFinally();
String output = getOutput();
String formOutput = getFormTag(output);
assertContainsAttribute(formOutput, "action", "/a%20b%20c");
}
private String getFormTag(String output) {
int inputStart = output.indexOf("<", 1);
int inputEnd = output.lastIndexOf(">", output.length() - 2);
return output.substring(0, inputStart) + output.substring(inputEnd + 1);
}
private String getInputTag(String output) {
int inputStart = output.indexOf("<", 1);
int inputEnd = output.lastIndexOf(">", output.length() - 2);
return output.substring(inputStart, inputEnd + 1);
}
private static void assertFormTagOpened(String output) {
assertTrue(output.startsWith("<form "));
}
private static void assertFormTagClosed(String output) {
assertTrue(output.endsWith("</form>"));
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_2083_1 |
crossvul-java_data_good_24_1 | package org.jolokia.util;
import java.util.regex.Pattern;
/**
* Helper class for handling proper response mime types
*
* @author roland
* @since 24.01.18
*/
public class MimeTypeUtil {
/**
* Extract the response mime type. This value is calculated for different situations:
* <p>
* <ul>
* <li>If a callback is given and its valid, the mime type is "text/javascript"</li>
* <li>Otherwise:
* <ul>
* <li>If a valid mimeType is given in the request ("text/plain", "application/json"), then this
* mimet type is returned</li>
* <li>If another mimeType is given, then "text/plain" is used</li>
* <li>If no mimeType is given then a given default mime type is used, but also sanitized
* as described above</li>
* </ul>
* </li>
* </ul>
*
* @param pRequestMimeType the mimetype given in the request
* @param defaultMimeType the default mime type to use if none is given in the request
* @param pCallback a callback given (can be null)
*/
public static String getResponseMimeType(String pRequestMimeType, String defaultMimeType, String pCallback) {
// For a valid given callback, return "text/javascript" for proper inclusion
if (pCallback != null && isValidCallback(pCallback)) {
return "text/javascript";
}
// Pick up mime time from request, but sanitize
if (pRequestMimeType != null) {
return sanitize(pRequestMimeType);
}
// Use the given default mime type (possibly picked up from a configuration)
return sanitize(defaultMimeType);
}
private static String sanitize(String mimeType) {
for (String accepted : new String[]{
"application/json",
"text/plain"
}) {
if (accepted.equalsIgnoreCase(mimeType)) {
return accepted;
}
}
return "text/plain";
}
/**
* Check that a callback matches a javascript function name. The argument must be not null
*
* @param pCallback callback to verify
* @return true if valud, false otherwise
*/
public static boolean isValidCallback(String pCallback) {
Pattern validJavaScriptFunctionNamePattern =
Pattern.compile("^[$A-Z_][0-9A-Z_$]*$", Pattern.CASE_INSENSITIVE);
return validJavaScriptFunctionNamePattern.matcher(pCallback).matches();
}
} | ./CrossVul/dataset_final_sorted/CWE-79/java/good_24_1 |
crossvul-java_data_good_4174_2 | package org.mapfish.print.servlet;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Test;
import org.mapfish.print.AbstractMapfishSpringTest;
import org.mapfish.print.config.access.AccessAssertionTestUtil;
import org.mapfish.print.test.util.ImageSimilarity;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@ContextConfiguration(locations = {
MapPrinterServletSecurityTest.PRINT_CONTEXT
})
public class MapPrinterServletSecurityTest extends AbstractMapfishSpringTest {
public static final String PRINT_CONTEXT =
"classpath:org/mapfish/print/servlet/mapfish-print-servlet.xml";
@Autowired
private MapPrinterServlet servlet;
@Autowired
private ServletMapPrinterFactory printerFactory;
@After
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test(timeout = 60000)
public void testCreateReportAndGet_Success() throws Exception {
AccessAssertionTestUtil.setCreds("ROLE_USER", "ROLE_EDITOR");
setUpConfigFiles();
final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest();
final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse();
String requestData = loadRequestDataAsString();
this.servlet.createReportAndGetNoAppId("png", requestData, false,
servletCreateRequest, servletCreateResponse);
assertEquals(HttpStatus.OK.value(), servletCreateResponse.getStatus());
assertCorrectResponse(servletCreateResponse);
}
@Test(timeout = 60000, expected = AccessDeniedException.class)
public void testCreateReportAndGet_InsufficientPrivileges() throws Exception {
AccessAssertionTestUtil.setCreds("ROLE_USER");
setUpConfigFiles();
final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest();
final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse();
String requestData = loadRequestDataAsString();
this.servlet.createReportAndGetNoAppId("png", requestData, false,
servletCreateRequest, servletCreateResponse);
}
@Test(timeout = 60000, expected = AuthenticationCredentialsNotFoundException.class)
public void testCreateReportAndGet_NoCredentials() throws Exception {
setUpConfigFiles();
final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest();
final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse();
String requestData = loadRequestDataAsString();
this.servlet.createReportAndGetNoAppId("png", requestData, false,
servletCreateRequest, servletCreateResponse);
}
@Test(timeout = 60000)
public void testCreateReportAndGet_RequestAllowed_OtherGetDenied() throws Exception {
AccessAssertionTestUtil.setCreds("ROLE_USER", "ROLE_EDITOR");
setUpConfigFiles();
final MockHttpServletRequest servletCreateRequest = new MockHttpServletRequest();
final MockHttpServletResponse servletCreateResponse = new MockHttpServletResponse();
String requestData = loadRequestDataAsString();
this.servlet.createReport("png", requestData, servletCreateRequest, servletCreateResponse);
assertEquals(HttpStatus.OK.value(), servletCreateResponse.getStatus());
final JSONObject response = new JSONObject(servletCreateResponse.getContentAsString());
final String ref = response.getString(MapPrinterServlet.JSON_PRINT_JOB_REF);
String statusURL = response.getString(MapPrinterServlet.JSON_STATUS_LINK);
// wait until job is done
boolean done = false;
while (!done) {
MockHttpServletRequest servletStatusRequest = new MockHttpServletRequest("GET", statusURL);
MockHttpServletResponse servletStatusResponse = new MockHttpServletResponse();
servlet.getStatus(ref, servletStatusRequest, servletStatusResponse);
String contentAsString = servletStatusResponse.getContentAsString();
final PJsonObject statusJson = parseJSONObjectFromString(contentAsString);
assertTrue(statusJson.toString(), statusJson.has(MapPrinterServlet.JSON_DONE));
done = statusJson.getBool(MapPrinterServlet.JSON_DONE);
if (!done) {
Thread.sleep(500);
}
}
try {
AccessAssertionTestUtil.setCreds("ROLE_USER");
final MockHttpServletResponse getResponse1 = new MockHttpServletResponse();
this.servlet.getReport(ref, false, getResponse1);
fail("Expected an AccessDeniedException");
} catch (AccessDeniedException e) {
// good
}
SecurityContextHolder.clearContext();
try {
final MockHttpServletResponse getResponse2 = new MockHttpServletResponse();
this.servlet.getReport(ref, false, getResponse2);
assertEquals(HttpStatus.UNAUTHORIZED.value(), servletCreateResponse.getStatus());
fail("Expected an AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException e) {
// good
}
}
private byte[] assertCorrectResponse(MockHttpServletResponse servletGetReportResponse)
throws IOException {
byte[] report;
report = servletGetReportResponse.getContentAsByteArray();
final String contentType = servletGetReportResponse.getHeader("Content-Type");
assertEquals("image/png", contentType);
final Calendar instance = Calendar.getInstance();
int year = instance.get(Calendar.YEAR);
String fileName = servletGetReportResponse.getHeader("Content-disposition").split("=")[1];
assertEquals("test_report-" + year + ".png", fileName);
new ImageSimilarity(getFile(MapPrinterServletSecurityTest.class, "expectedSimpleImage.png"))
.assertSimilarity(report, 1);
return report;
}
private void setUpConfigFiles() throws URISyntaxException {
final HashMap<String, String> configFiles = new HashMap<>();
configFiles.put("default",
getFile(MapPrinterServletSecurityTest.class, "config-security.yaml")
.getAbsolutePath());
printerFactory.setConfigurationFiles(configFiles);
}
private String loadRequestDataAsString() throws IOException {
final PJsonObject requestJson =
parseJSONObjectFromFile(MapPrinterServletSecurityTest.class, "requestData.json");
return requestJson.getInternalObj().toString();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_4174_2 |
crossvul-java_data_good_2083_0 | /*
* Copyright 2002-2014 the original author or authors.
*
* 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 org.springframework.web.servlet.tags.form;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.Conventions;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.UriUtils;
/**
* Databinding-aware JSP tag for rendering an HTML '{@code form}' whose
* inner elements are bound to properties on a <em>form object</em>.
*
* <p>Users should place the form object into the
* {@link org.springframework.web.servlet.ModelAndView ModelAndView} when
* populating the data for their view. The name of this form object can be
* configured using the {@link #setModelAttribute "modelAttribute"} property.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Scott Andrews
* @author Rossen Stoyanchev
* @since 2.0
*/
@SuppressWarnings("serial")
public class FormTag extends AbstractHtmlElementTag {
/** The default HTTP method using which form values are sent to the server: "post" */
private static final String DEFAULT_METHOD = "post";
/** The default attribute name: "command" */
public static final String DEFAULT_COMMAND_NAME = "command";
/** The name of the '{@code modelAttribute}' setting */
private static final String MODEL_ATTRIBUTE = "modelAttribute";
/**
* The name of the {@link javax.servlet.jsp.PageContext} attribute under which the
* form object name is exposed.
*/
public static final String MODEL_ATTRIBUTE_VARIABLE_NAME =
Conventions.getQualifiedAttributeName(AbstractFormTag.class, MODEL_ATTRIBUTE);
/** Default method parameter, i.e. {@code _method}. */
private static final String DEFAULT_METHOD_PARAM = "_method";
private static final String FORM_TAG = "form";
private static final String INPUT_TAG = "input";
private static final String ACTION_ATTRIBUTE = "action";
private static final String METHOD_ATTRIBUTE = "method";
private static final String TARGET_ATTRIBUTE = "target";
private static final String ENCTYPE_ATTRIBUTE = "enctype";
private static final String ACCEPT_CHARSET_ATTRIBUTE = "accept-charset";
private static final String ONSUBMIT_ATTRIBUTE = "onsubmit";
private static final String ONRESET_ATTRIBUTE = "onreset";
private static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
private static final String NAME_ATTRIBUTE = "name";
private static final String VALUE_ATTRIBUTE = "value";
private static final String TYPE_ATTRIBUTE = "type";
private TagWriter tagWriter;
private String modelAttribute = DEFAULT_COMMAND_NAME;
private String name;
private String action;
private String servletRelativeAction;
private String method = DEFAULT_METHOD;
private String target;
private String enctype;
private String acceptCharset;
private String onsubmit;
private String onreset;
private String autocomplete;
private String methodParam = DEFAULT_METHOD_PARAM;
/** Caching a previous nested path, so that it may be reset */
private String previousNestedPath;
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
*/
public void setModelAttribute(String modelAttribute) {
this.modelAttribute = modelAttribute;
}
/**
* Get the name of the form attribute in the model.
*/
protected String getModelAttribute() {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* @see #setModelAttribute
*/
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* @see #getModelAttribute
*/
protected String getCommandName() {
return this.modelAttribute;
}
/**
* Set the value of the '{@code name}' attribute.
* <p>May be a runtime expression.
* <p>Name is not a valid attribute for form on XHTML 1.0. However,
* it is sometimes needed for backward compatibility.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the value of the '{@code name}' attribute.
*/
@Override
protected String getName() throws JspException {
return this.name;
}
/**
* Set the value of the '{@code action}' attribute.
* <p>May be a runtime expression.
*/
public void setAction(String action) {
this.action = (action != null ? action : "");
}
/**
* Get the value of the '{@code action}' attribute.
*/
protected String getAction() {
return this.action;
}
/**
* Set the value of the '{@code action}' attribute.
* <p>May be a runtime expression.
*/
public void setServletRelativeAction(String servletRelativeaction) {
this.servletRelativeAction = (servletRelativeaction != null ? servletRelativeaction : "");
}
/**
* Get the value of the '{@code action}' attribute.
*/
protected String getServletRelativeAction() {
return this.servletRelativeAction;
}
/**
* Set the value of the '{@code method}' attribute.
* <p>May be a runtime expression.
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Get the value of the '{@code method}' attribute.
*/
protected String getMethod() {
return this.method;
}
/**
* Set the value of the '{@code target}' attribute.
* <p>May be a runtime expression.
*/
public void setTarget(String target) {
this.target = target;
}
/**
* Get the value of the '{@code target}' attribute.
*/
public String getTarget() {
return this.target;
}
/**
* Set the value of the '{@code enctype}' attribute.
* <p>May be a runtime expression.
*/
public void setEnctype(String enctype) {
this.enctype = enctype;
}
/**
* Get the value of the '{@code enctype}' attribute.
*/
protected String getEnctype() {
return this.enctype;
}
/**
* Set the value of the '{@code acceptCharset}' attribute.
* <p>May be a runtime expression.
*/
public void setAcceptCharset(String acceptCharset) {
this.acceptCharset = acceptCharset;
}
/**
* Get the value of the '{@code acceptCharset}' attribute.
*/
protected String getAcceptCharset() {
return this.acceptCharset;
}
/**
* Set the value of the '{@code onsubmit}' attribute.
* <p>May be a runtime expression.
*/
public void setOnsubmit(String onsubmit) {
this.onsubmit = onsubmit;
}
/**
* Get the value of the '{@code onsubmit}' attribute.
*/
protected String getOnsubmit() {
return this.onsubmit;
}
/**
* Set the value of the '{@code onreset}' attribute.
* <p>May be a runtime expression.
*/
public void setOnreset(String onreset) {
this.onreset = onreset;
}
/**
* Get the value of the '{@code onreset}' attribute.
*/
protected String getOnreset() {
return this.onreset;
}
/**
* Set the value of the '{@code autocomplete}' attribute.
* May be a runtime expression.
*/
public void setAutocomplete(String autocomplete) {
this.autocomplete = autocomplete;
}
/**
* Get the value of the '{@code autocomplete}' attribute.
*/
protected String getAutocomplete() {
return this.autocomplete;
}
/**
* Set the name of the request param for non-browser supported HTTP methods.
*/
public void setMethodParam(String methodParam) {
this.methodParam = methodParam;
}
/**
* Get the name of the request param for non-browser supported HTTP methods.
*/
protected String getMethodParameter() {
return this.methodParam;
}
/**
* Determine if the HTTP method is supported by browsers (i.e. GET or POST).
*/
protected boolean isMethodBrowserSupported(String method) {
return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method));
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParameter();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
private String getHttpMethod() {
return isMethodBrowserSupported(getMethod()) ? getMethod() : DEFAULT_METHOD;
}
private void assertHttpMethod(String method) {
for (HttpMethod httpMethod : HttpMethod.values()) {
if (httpMethod.name().equalsIgnoreCase(method)) {
return;
}
}
throw new IllegalArgumentException("Invalid HTTP method: " + method);
}
/**
* Autogenerated IDs correspond to the form object name.
*/
@Override
protected String autogenerateId() throws JspException {
return resolveModelAttribute();
}
/**
* {@link #evaluate Resolves} and returns the name of the form object.
* @throws IllegalArgumentException if the form object resolves to {@code null}
*/
protected String resolveModelAttribute() throws JspException {
Object resolvedModelAttribute = evaluate(MODEL_ATTRIBUTE, getModelAttribute());
if (resolvedModelAttribute == null) {
throw new IllegalArgumentException(MODEL_ATTRIBUTE + " must not be null");
}
return (String) resolvedModelAttribute;
}
/**
* Resolve the value of the '{@code action}' attribute.
* <p>If the user configured an '{@code action}' value then the result of
* evaluating this value is used. If the user configured an
* '{@code servletRelativeAction}' value then the value is prepended
* with the context and servlet paths, and the result is used. Otherwise, the
* {@link org.springframework.web.servlet.support.RequestContext#getRequestUri()
* originating URI} is used.
*
* @return the value that is to be used for the '{@code action}' attribute
*/
protected String resolveAction() throws JspException {
String action = getAction();
String servletRelativeAction = getServletRelativeAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else if (StringUtils.hasText(servletRelativeAction)) {
String pathToServlet = getRequestContext().getPathToServlet();
if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
servletRelativeAction = pathToServlet + servletRelativeAction;
}
servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
return processAction(servletRelativeAction);
}
else {
String requestUri = getRequestContext().getRequestUri();
String encoding = pageContext.getResponse().getCharacterEncoding();
try {
requestUri = UriUtils.encodePath(requestUri, encoding);
}
catch (UnsupportedEncodingException e) {
throw new JspException(e);
}
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
/**
* Process the action through a {@link RequestDataValueProcessor} instance
* if one is configured or otherwise returns the action unmodified.
*/
private String processAction(String action) {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
action = processor.processAction((HttpServletRequest) request, action, getHttpMethod());
}
return action;
}
/**
* Closes the '{@code form}' block tag and removes the form object name
* from the {@link javax.servlet.jsp.PageContext}.
*/
@Override
public int doEndTag() throws JspException {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
writeHiddenFields(processor.getExtraHiddenFields((HttpServletRequest) request));
}
this.tagWriter.endTag();
return EVAL_PAGE;
}
/**
* Writes the given values as hidden fields.
*/
private void writeHiddenFields(Map<String, String> hiddenFields) throws JspException {
if (hiddenFields != null) {
this.tagWriter.appendValue("<div>\n");
for (String name : hiddenFields.keySet()) {
this.tagWriter.appendValue("<input type=\"hidden\" ");
this.tagWriter.appendValue("name=\"" + name + "\" value=\"" + hiddenFields.get(name) + "\" ");
this.tagWriter.appendValue("/>\n");
}
this.tagWriter.appendValue("</div>");
}
}
/**
* Clears the stored {@link TagWriter}.
*/
@Override
public void doFinally() {
super.doFinally();
this.pageContext.removeAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
if (this.previousNestedPath != null) {
// Expose previous nestedPath value.
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, this.previousNestedPath, PageContext.REQUEST_SCOPE);
}
else {
// Remove exposed nestedPath value.
this.pageContext.removeAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
}
this.tagWriter = null;
this.previousNestedPath = null;
}
/**
* Override resolve CSS class since error class is not supported.
*/
@Override
protected String resolveCssClass() throws JspException {
return ObjectUtils.getDisplayString(evaluate("cssClass", getCssClass()));
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setPath(String path) {
throw new UnsupportedOperationException("The 'path' attribute is not supported for forms");
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setCssErrorClass(String cssErrorClass) {
throw new UnsupportedOperationException("The 'cssErrorClass' attribute is not supported for forms");
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_2083_0 |
crossvul-java_data_good_2097_0 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Yahoo! Inc., Stephen Connolly, Tom Huybrechts, Alan Harder, Manufacture
* Francaise des Pneumatiques Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import hudson.cli.CLICommand;
import hudson.console.ConsoleAnnotationDescriptor;
import hudson.console.ConsoleAnnotatorFactory;
import hudson.model.*;
import hudson.model.ParameterDefinition.ParameterDescriptor;
import hudson.search.SearchableModelObject;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.GlobalSecurityConfiguration;
import hudson.security.Permission;
import hudson.security.SecurityRealm;
import hudson.security.captcha.CaptchaSupport;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.tasks.UserAvatarResolver;
import hudson.util.Area;
import hudson.util.Iterators;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.Secret;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.RenderOnDemandClosure;
import jenkins.model.GlobalConfiguration;
import jenkins.model.GlobalConfigurationCategory;
import jenkins.model.GlobalConfigurationCategory.Unclassified;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithContextMenu;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.jexl.parser.ASTSizeFunction;
import org.apache.commons.jexl.util.Introspector;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.jvnet.tiger_types.Types;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgument;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Utility functions used in views.
*
* <p>
* An instance of this class is created for each request and made accessible
* from view pages via the variable 'h' (h stands for Hudson.)
*
* @author Kohsuke Kawaguchi
*/
public class Functions {
private static volatile int globalIota = 0;
private int iota;
public Functions() {
iota = globalIota;
// concurrent requests can use the same ID --- we are just trying to
// prevent the same user from seeing the same ID repeatedly.
globalIota+=1000;
}
/**
* Generates an unique ID.
*/
public String generateId() {
return "id"+iota++;
}
public static boolean isModel(Object o) {
return o instanceof ModelObject;
}
public static boolean isModelWithContextMenu(Object o) {
return o instanceof ModelObjectWithContextMenu;
}
public static String xsDate(Calendar cal) {
return Util.XS_DATETIME_FORMATTER.format(cal.getTime());
}
public static String rfc822Date(Calendar cal) {
return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime());
}
public static void initPageVariables(JellyContext context) {
String rootURL = Stapler.getCurrentRequest().getContextPath();
Functions h = new Functions();
context.setVariable("h", h);
// The path starts with a "/" character but does not end with a "/" character.
context.setVariable("rootURL", rootURL);
/*
load static resources from the path dedicated to a specific version.
This "/static/VERSION/abc/def.ghi" path is interpreted by stapler to be
the same thing as "/abc/def.ghi", but this avoids the stale cache
problem when the user upgrades to new Jenkins. Stapler also sets a long
future expiration dates for such static resources.
see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML
*/
context.setVariable("resURL",rootURL+getResourcePath());
context.setVariable("imagesURL",rootURL+getResourcePath()+"/images");
}
/**
* Given {@code c=MyList (extends ArrayList<Foo>), base=List}, compute the parameterization of 'base'
* that's assignable from 'c' (in this case {@code List<Foo>}), and return its n-th type parameter
* (n=0 would return {@code Foo}).
*
* <p>
* This method is useful for doing type arithmetic.
*
* @throws AssertionError
* if c' is not parameterized.
*/
public static <B> Class getTypeParameter(Class<? extends B> c, Class<B> base, int n) {
Type parameterization = Types.getBaseClass(c,base);
if (parameterization instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) parameterization;
return Types.erasure(Types.getTypeArgument(pt,n));
} else {
throw new AssertionError(c+" doesn't properly parameterize "+base);
}
}
public JDK.DescriptorImpl getJDKDescriptor() {
return Jenkins.getInstance().getDescriptorByType(JDK.DescriptorImpl.class);
}
/**
* Prints the integer as a string that represents difference,
* like "-5", "+/-0", "+3".
*/
public static String getDiffString(int i) {
if(i==0) return "\u00B10"; // +/-0
String s = Integer.toString(i);
if(i>0) return "+"+s;
else return s;
}
/**
* {@link #getDiffString(int)} that doesn't show anything for +/-0
*/
public static String getDiffString2(int i) {
if(i==0) return "";
String s = Integer.toString(i);
if(i>0) return "+"+s;
else return s;
}
/**
* {@link #getDiffString2(int)} that puts the result into prefix and suffix
* if there's something to print
*/
public static String getDiffString2(String prefix, int i, String suffix) {
if(i==0) return "";
String s = Integer.toString(i);
if(i>0) return prefix+"+"+s+suffix;
else return prefix+s+suffix;
}
/**
* Adds the proper suffix.
*/
public static String addSuffix(int n, String singular, String plural) {
StringBuilder buf = new StringBuilder();
buf.append(n).append(' ');
if(n==1)
buf.append(singular);
else
buf.append(plural);
return buf.toString();
}
public static RunUrl decompose(StaplerRequest req) {
List<Ancestor> ancestors = req.getAncestors();
// find the first and last Run instances
Ancestor f=null,l=null;
for (Ancestor anc : ancestors) {
if(anc.getObject() instanceof Run) {
if(f==null) f=anc;
l=anc;
}
}
if(l==null) return null; // there was no Run object
String head = f.getPrev().getUrl()+'/';
String base = l.getUrl();
String reqUri = req.getOriginalRequestURI();
// Find "rest" or URI by removing N path components.
// Not using reqUri.substring(f.getUrl().length()) to avoid mismatches due to
// url-encoding or extra slashes. Former may occur in Tomcat (despite the spec saying
// this string is not decoded, Tomcat apparently decodes this string. You see ' '
// instead of '%20', which is what the browser has sent), latter may occur in some
// proxy or URL-rewriting setups where extra slashes are inadvertently added.
String furl = f.getUrl();
int slashCount = 0;
// Count components in ancestor URL
for (int i = furl.indexOf('/'); i >= 0; i = furl.indexOf('/', i + 1)) slashCount++;
// Remove that many from request URL, ignoring extra slashes
String rest = reqUri.replaceFirst("(?:/+[^/]*){" + slashCount + "}", "");
return new RunUrl( (Run) f.getObject(), head, base, rest);
}
/**
* If we know the user's screen resolution, return it. Otherwise null.
* @since 1.213
*/
public static Area getScreenResolution() {
Cookie res = Functions.getCookie(Stapler.getCurrentRequest(),"screenResolution");
if(res!=null)
return Area.parse(res.getValue());
return null;
}
/**
* URL decomposed for easier computation of relevant URLs.
*
* <p>
* The decomposed URL will be of the form:
* <pre>
* aaaaaa/524/bbbbb/cccc
* -head-| N |---rest---
* ----- base -----|
* </pre>
*
* <p>
* The head portion is the part of the URL from the {@link jenkins.model.Jenkins}
* object to the first {@link Run} subtype. When "next/prev build"
* is chosen, this part remains intact.
*
* <p>
* The <tt>524</tt> is the path from {@link Job} to {@link Run}.
*
* <p>
* The <tt>bbb</tt> portion is the path after that till the last
* {@link Run} subtype. The <tt>ccc</tt> portion is the part
* after that.
*/
public static final class RunUrl {
private final String head, base, rest;
private final Run run;
public RunUrl(Run run, String head, String base, String rest) {
this.run = run;
this.head = head;
this.base = base;
this.rest = rest;
}
public String getBaseUrl() {
return base;
}
/**
* Returns the same page in the next build.
*/
public String getNextBuildUrl() {
return getUrl(run.getNextBuild());
}
/**
* Returns the same page in the previous build.
*/
public String getPreviousBuildUrl() {
return getUrl(run.getPreviousBuild());
}
private String getUrl(Run n) {
if(n ==null)
return null;
else {
return head+n.getNumber()+rest;
}
}
}
public static Node.Mode[] getNodeModes() {
return Node.Mode.values();
}
public static String getProjectListString(List<Project> projects) {
return Items.toNameList(projects);
}
/**
* @deprecated as of 1.294
* JEXL now supports the real ternary operator "x?y:z", so this work around
* is no longer necessary.
*/
public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) {
return cond ? thenValue : elseValue;
}
public static String appendIfNotNull(String text, String suffix, String nullText) {
return text == null ? nullText : text + suffix;
}
public static Map getSystemProperties() {
return new TreeMap<Object,Object>(System.getProperties());
}
public static Map getEnvVars() {
return new TreeMap<String,String>(EnvVars.masterEnvVars);
}
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
public static List<LogRecord> getLogRecords() {
return Jenkins.logRecords;
}
public static String printLogRecord(LogRecord r) {
return formatter.format(r);
}
public static Cookie getCookie(HttpServletRequest req,String name) {
Cookie[] cookies = req.getCookies();
if(cookies!=null) {
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
public static String getCookie(HttpServletRequest req,String name, String defaultValue) {
Cookie c = getCookie(req, name);
if(c==null || c.getValue()==null) return defaultValue;
return c.getValue();
}
private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
@Restricted(NoExternalUse.class)
public static String validateIconSize(String iconSize) throws SecurityException {
if (!ICON_SIZE.matcher(iconSize).matches()) {
throw new SecurityException("invalid iconSize");
}
return iconSize;
}
/**
* Gets the suffix to use for YUI JavaScript.
*/
public static String getYuiSuffix() {
return DEBUG_YUI ? "debug" : "min";
}
/**
* Set to true if you need to use the debug version of YUI.
*/
public static boolean DEBUG_YUI = Boolean.getBoolean("debug.YUI");
/**
* Creates a sub map by using the given range (both ends inclusive).
*/
public static <V> SortedMap<Integer,V> filter(SortedMap<Integer,V> map, String from, String to) {
if(from==null && to==null) return map;
if(to==null)
return map.headMap(Integer.parseInt(from)-1);
if(from==null)
return map.tailMap(Integer.parseInt(to));
return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1);
}
private static final SimpleFormatter formatter = new SimpleFormatter();
/**
* Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
*
* @param noAutoRefresh
* On certain pages, like a page with forms, will have annoying interference
* with auto refresh. On those pages, disable auto-refresh.
*/
public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response, boolean noAutoRefresh) {
if(noAutoRefresh)
return;
String param = request.getParameter("auto_refresh");
boolean refresh = isAutoRefresh(request);
if (param != null) {
refresh = Boolean.parseBoolean(param);
Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh));
// Need to set path or it will not stick from e.g. a project page to the dashboard.
// Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
// to avoid conflicts with any other web apps that might be on the same machine.
c.setPath("/");
c.setMaxAge(60*60*24*30); // persist it roughly for a month
response.addCookie(c);
}
if (refresh) {
response.addHeader("Refresh", System.getProperty("hudson.Functions.autoRefreshSeconds", "10"));
}
}
public static boolean isAutoRefresh(HttpServletRequest request) {
String param = request.getParameter("auto_refresh");
if (param != null) {
return Boolean.parseBoolean(param);
}
Cookie[] cookies = request.getCookies();
if(cookies==null)
return false; // when API design messes it up, we all suffer
for (Cookie c : cookies) {
if (c.getName().equals("hudson_auto_refresh")) {
return Boolean.parseBoolean(c.getValue());
}
}
return false;
}
/**
* Finds the given object in the ancestor list and returns its URL.
* This is used to determine the "current" URL assigned to the given object,
* so that one can compute relative URLs from it.
*/
public static String getNearestAncestorUrl(StaplerRequest req,Object it) {
List list = req.getAncestors();
for( int i=list.size()-1; i>=0; i-- ) {
Ancestor anc = (Ancestor) list.get(i);
if(anc.getObject()==it)
return anc.getUrl();
}
return null;
}
/**
* Finds the inner-most {@link SearchableModelObject} in scope.
*/
public static String getSearchURL() {
List list = Stapler.getCurrentRequest().getAncestors();
for( int i=list.size()-1; i>=0; i-- ) {
Ancestor anc = (Ancestor) list.get(i);
if(anc.getObject() instanceof SearchableModelObject)
return anc.getUrl()+"/search/";
}
return null;
}
public static String appendSpaceIfNotNull(String n) {
if(n==null) return null;
else return n+' ';
}
/**
* One nbsp per 10 pixels in given size, which may be a plain number or "NxN"
* (like an iconSize). Useful in a sortable table heading.
*/
public static String nbspIndent(String size) {
int i = size.indexOf('x');
i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10;
StringBuilder buf = new StringBuilder(30);
for (int j = 0; j < i; j++)
buf.append(" ");
return buf.toString();
}
public static String getWin32ErrorMessage(IOException e) {
return Util.getWin32ErrorMessage(e);
}
public static boolean isMultiline(String s) {
if(s==null) return false;
return s.indexOf('\r')>=0 || s.indexOf('\n')>=0;
}
public static String encode(String s) {
return Util.encode(s);
}
public static String escape(String s) {
return Util.escape(s);
}
public static String xmlEscape(String s) {
return Util.xmlEscape(s);
}
public static String xmlUnescape(String s) {
return s.replace("<","<").replace(">",">").replace("&","&");
}
public static String htmlAttributeEscape(String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='<')
buf.append("<");
else
if(ch=='>')
buf.append(">");
else
if(ch=='&')
buf.append("&");
else
if(ch=='"')
buf.append(""");
else
if(ch=='\'')
buf.append("'");
else
buf.append(ch);
}
return buf.toString();
}
public static void checkPermission(Permission permission) throws IOException, ServletException {
checkPermission(Jenkins.getInstance(),permission);
}
public static void checkPermission(AccessControlled object, Permission permission) throws IOException, ServletException {
if (permission != null) {
object.checkPermission(permission);
}
}
/**
* This version is so that the 'checkPermission' on <tt>layout.jelly</tt>
* degrades gracefully if "it" is not an {@link AccessControlled} object.
* Otherwise it will perform no check and that problem is hard to notice.
*/
public static void checkPermission(Object object, Permission permission) throws IOException, ServletException {
if (permission == null)
return;
if (object instanceof AccessControlled)
checkPermission((AccessControlled) object,permission);
else {
List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors();
for(Ancestor anc : Iterators.reverse(ancs)) {
Object o = anc.getObject();
if (o instanceof AccessControlled) {
checkPermission((AccessControlled) o,permission);
return;
}
}
checkPermission(Jenkins.getInstance(),permission);
}
}
/**
* Returns true if the current user has the given permission.
*
* @param permission
* If null, returns true. This defaulting is convenient in making the use of this method terse.
*/
public static boolean hasPermission(Permission permission) throws IOException, ServletException {
return hasPermission(Jenkins.getInstance(),permission);
}
/**
* This version is so that the 'hasPermission' can degrade gracefully
* if "it" is not an {@link AccessControlled} object.
*/
public static boolean hasPermission(Object object, Permission permission) throws IOException, ServletException {
if (permission == null)
return true;
if (object instanceof AccessControlled)
return ((AccessControlled)object).hasPermission(permission);
else {
List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors();
for(Ancestor anc : Iterators.reverse(ancs)) {
Object o = anc.getObject();
if (o instanceof AccessControlled) {
return ((AccessControlled)o).hasPermission(permission);
}
}
return Jenkins.getInstance().hasPermission(permission);
}
}
public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, ServletException {
// this is legacy --- all views should be eventually converted to
// the permission based model.
if(required!=null && !Hudson.adminCheck(req, rsp)) {
// check failed. commit the FORBIDDEN response, then abort.
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.getOutputStream().close();
throw new ServletException("Unauthorized access");
}
// make sure the user owns the necessary permission to access this page.
if(permission!=null)
checkPermission(permission);
}
/**
* Infers the hudson installation URL from the given request.
*/
public static String inferHudsonURL(StaplerRequest req) {
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl !=null)
// prefer the one explicitly configured, to work with load-balancer, frontend, etc.
return rootUrl;
StringBuilder buf = new StringBuilder();
buf.append(req.getScheme()).append("://");
buf.append(req.getServerName());
if(! (req.getScheme().equals("http") && req.getLocalPort()==80 || req.getScheme().equals("https") && req.getLocalPort()==443))
buf.append(':').append(req.getLocalPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Returns the link to be displayed in the footer of the UI.
*/
public static String getFooterURL() {
if(footerURL == null) {
footerURL = System.getProperty("hudson.footerURL");
if(StringUtils.isBlank(footerURL)) {
footerURL = "http://jenkins-ci.org/";
}
}
return footerURL;
}
private static String footerURL = null;
public static List<JobPropertyDescriptor> getJobPropertyDescriptors(Class<? extends Job> clazz) {
return JobPropertyDescriptor.getPropertyDescriptors(clazz);
}
public static List<Descriptor<BuildWrapper>> getBuildWrapperDescriptors(AbstractProject<?,?> project) {
return BuildWrappers.getFor(project);
}
public static List<Descriptor<SecurityRealm>> getSecurityRealmDescriptors() {
return SecurityRealm.all();
}
public static List<Descriptor<AuthorizationStrategy>> getAuthorizationStrategyDescriptors() {
return AuthorizationStrategy.all();
}
public static List<Descriptor<Builder>> getBuilderDescriptors(AbstractProject<?,?> project) {
return BuildStepDescriptor.filter(Builder.all(), project.getClass());
}
public static List<Descriptor<Publisher>> getPublisherDescriptors(AbstractProject<?,?> project) {
return BuildStepDescriptor.filter(Publisher.all(), project.getClass());
}
public static List<SCMDescriptor<?>> getSCMDescriptors(AbstractProject<?,?> project) {
return SCM._for(project);
}
public static List<Descriptor<ComputerLauncher>> getComputerLauncherDescriptors() {
return Jenkins.getInstance().<ComputerLauncher,Descriptor<ComputerLauncher>>getDescriptorList(ComputerLauncher.class);
}
public static List<Descriptor<RetentionStrategy<?>>> getRetentionStrategyDescriptors() {
return RetentionStrategy.all();
}
public static List<ParameterDescriptor> getParameterDescriptors() {
return ParameterDefinition.all();
}
public static List<Descriptor<CaptchaSupport>> getCaptchaSupportDescriptors() {
return CaptchaSupport.all();
}
public static List<Descriptor<ViewsTabBar>> getViewsTabBarDescriptors() {
return ViewsTabBar.all();
}
public static List<Descriptor<MyViewsTabBar>> getMyViewsTabBarDescriptors() {
return MyViewsTabBar.all();
}
public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) {
List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>();
Collection<NodePropertyDescriptor> list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : list) {
if (npd.isApplicable(clazz)) {
result.add(npd);
}
}
return result;
}
/**
* Gets all the descriptors sorted by their inheritance tree of {@link Describable}
* so that descriptors of similar types come nearby.
*
* <p>
* We sort them by {@link Extension#ordinal()} but only for {@link GlobalConfiguration}s,
* as the value is normally used to compare similar kinds of extensions, and we needed
* {@link GlobalConfiguration}s to be able to position themselves in a layer above.
* This however creates some asymmetry between regular {@link Descriptor}s and {@link GlobalConfiguration}s.
* Perhaps it is better to introduce another annotation element? But then,
* extensions shouldn't normally concern themselves about ordering too much, and the only reason
* we needed this for {@link GlobalConfiguration}s are for backward compatibility.
*
* @param predicate
* Filter the descriptors based on {@link GlobalConfigurationCategory}
* @since 1.494
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig(Predicate<GlobalConfigurationCategory> predicate) {
ExtensionList<Descriptor> exts = Jenkins.getInstance().getExtensionList(Descriptor.class);
List<Tag> r = new ArrayList<Tag>(exts.size());
for (ExtensionComponent<Descriptor> c : exts.getComponents()) {
Descriptor d = c.getInstance();
if (d.getGlobalConfigPage()==null) continue;
if (d instanceof GlobalConfiguration) {
if (predicate.apply(((GlobalConfiguration)d).getCategory()))
r.add(new Tag(c.ordinal(), d));
} else {
if (predicate.apply(GlobalConfigurationCategory.get(Unclassified.class)))
r.add(new Tag(0, d));
}
}
Collections.sort(r);
List<Descriptor> answer = new ArrayList<Descriptor>(r.size());
for (Tag d : r) answer.add(d.d);
return DescriptorVisibilityFilter.apply(Jenkins.getInstance(),answer);
}
/**
* Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but with a constant truth predicate, to include all descriptors.
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig() {
return getSortedDescriptorsForGlobalConfig(Predicates.<GlobalConfigurationCategory>alwaysTrue());
}
/**
* @deprecated This is rather meaningless.
*/
@Deprecated
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigNoSecurity() {
return getSortedDescriptorsForGlobalConfig(Predicates.not(GlobalSecurityConfiguration.FILTER));
}
/**
* Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but for unclassified descriptors only.
* @since 1.506
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassified() {
return getSortedDescriptorsForGlobalConfig(new Predicate<GlobalConfigurationCategory>() {
public boolean apply(GlobalConfigurationCategory cat) {
return cat instanceof GlobalConfigurationCategory.Unclassified;
}
});
}
private static class Tag implements Comparable<Tag> {
double ordinal;
String hierarchy;
Descriptor d;
Tag(double ordinal, Descriptor d) {
this.ordinal = ordinal;
this.d = d;
this.hierarchy = buildSuperclassHierarchy(d.clazz, new StringBuilder()).toString();
}
private StringBuilder buildSuperclassHierarchy(Class c, StringBuilder buf) {
Class sc = c.getSuperclass();
if (sc!=null) buildSuperclassHierarchy(sc,buf).append(':');
return buf.append(c.getName());
}
public int compareTo(Tag that) {
int r = Double.compare(this.ordinal, that.ordinal);
if (r!=0) return -r; // descending for ordinal
return this.hierarchy.compareTo(that.hierarchy);
}
}
/**
* Computes the path to the icon of the given action
* from the context path.
*/
public static String getIconFilePath(Action a) {
String name = a.getIconFileName();
if (name==null) return null;
if (name.startsWith("/"))
return name.substring(1);
else
return "images/24x24/"+name;
}
/**
* Works like JSTL build-in size(x) function,
* but handle null gracefully.
*/
public static int size2(Object o) throws Exception {
if(o==null) return 0;
return ASTSizeFunction.sizeOf(o,Introspector.getUberspect());
}
/**
* Computes the relative path from the current page to the given item.
*/
public static String getRelativeLinkTo(Item p) {
Map<Object,String> ancestors = new HashMap<Object,String>();
View view=null;
StaplerRequest request = Stapler.getCurrentRequest();
for( Ancestor a : request.getAncestors() ) {
ancestors.put(a.getObject(),a.getRelativePath());
if(a.getObject() instanceof View)
view = (View) a.getObject();
}
String path = ancestors.get(p);
if(path!=null) return path;
Item i=p;
String url = "";
while(true) {
ItemGroup ig = i.getParent();
url = i.getShortUrl()+url;
if(ig== Jenkins.getInstance()) {
assert i instanceof TopLevelItem;
if(view!=null && view.contains((TopLevelItem)i)) {
// if p and the current page belongs to the same view, then return a relative path
return ancestors.get(view)+'/'+url;
} else {
// otherwise return a path from the root Hudson
return request.getContextPath()+'/'+p.getUrl();
}
}
path = ancestors.get(ig);
if(path!=null) return path+'/'+url;
assert ig instanceof Item; // if not, ig must have been the Hudson instance
i = (Item) ig;
}
}
public static Map<Thread,StackTraceElement[]> dumpAllThreads() {
Map<Thread,StackTraceElement[]> sorted = new TreeMap<Thread,StackTraceElement[]>(new ThreadSorter());
sorted.putAll(Thread.getAllStackTraces());
return sorted;
}
@IgnoreJRERequirement
public static ThreadInfo[] getThreadInfos() {
ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(),mbean.isSynchronizerUsageSupported());
}
public static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) {
ThreadGroupMap sorter = new ThreadGroupMap();
Arrays.sort(list, sorter);
return sorter;
}
// Common code for sorting Threads/ThreadInfos by ThreadGroup
private static class ThreadSorterBase {
protected Map<Long,String> map = new HashMap<Long,String>();
private ThreadSorterBase() {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while (tg.getParent() != null) tg = tg.getParent();
Thread[] threads = new Thread[tg.activeCount()*2];
int threadsLen = tg.enumerate(threads, true);
for (int i = 0; i < threadsLen; i++)
map.put(threads[i].getId(), threads[i].getThreadGroup().getName());
}
protected int compare(long idA, long idB) {
String tga = map.get(idA), tgb = map.get(idB);
int result = (tga!=null?-1:0) + (tgb!=null?1:0); // Will be non-zero if only one is null
if (result==0 && tga!=null)
result = tga.compareToIgnoreCase(tgb);
return result;
}
}
public static class ThreadGroupMap extends ThreadSorterBase implements Comparator<ThreadInfo> {
/**
* @return ThreadGroup name or null if unknown
*/
public String getThreadGroup(ThreadInfo ti) {
return map.get(ti.getThreadId());
}
public int compare(ThreadInfo a, ThreadInfo b) {
int result = compare(a.getThreadId(), b.getThreadId());
if (result == 0)
result = a.getThreadName().compareToIgnoreCase(b.getThreadName());
return result;
}
}
private static class ThreadSorter extends ThreadSorterBase implements Comparator<Thread> {
public int compare(Thread a, Thread b) {
int result = compare(a.getId(), b.getId());
if (result == 0)
result = a.getName().compareToIgnoreCase(b.getName());
return result;
}
}
/**
* Are we running on JRE6 or above?
*/
@IgnoreJRERequirement
public static boolean isMustangOrAbove() {
try {
System.console();
return true;
} catch(LinkageError e) {
return false;
}
}
// ThreadInfo.toString() truncates the stack trace by first 8, so needed my own version
@IgnoreJRERequirement
public static String dumpThreadInfo(ThreadInfo ti, ThreadGroupMap map) {
String grp = map.getThreadGroup(ti);
StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"" +
" Id=" + ti.getThreadId() + " Group=" +
(grp != null ? grp : "?") + " " +
ti.getThreadState());
if (ti.getLockName() != null) {
sb.append(" on " + ti.getLockName());
}
if (ti.getLockOwnerName() != null) {
sb.append(" owned by \"" + ti.getLockOwnerName() +
"\" Id=" + ti.getLockOwnerId());
}
if (ti.isSuspended()) {
sb.append(" (suspended)");
}
if (ti.isInNative()) {
sb.append(" (in native)");
}
sb.append('\n');
StackTraceElement[] stackTrace = ti.getStackTrace();
for (int i=0; i < stackTrace.length; i++) {
StackTraceElement ste = stackTrace[i];
sb.append("\tat " + ste.toString());
sb.append('\n');
if (i == 0 && ti.getLockInfo() != null) {
Thread.State ts = ti.getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on " + ti.getLockInfo());
sb.append('\n');
break;
case WAITING:
sb.append("\t- waiting on " + ti.getLockInfo());
sb.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on " + ti.getLockInfo());
sb.append('\n');
break;
default:
}
}
for (MonitorInfo mi : ti.getLockedMonitors()) {
if (mi.getLockedStackDepth() == i) {
sb.append("\t- locked " + mi);
sb.append('\n');
}
}
}
LockInfo[] locks = ti.getLockedSynchronizers();
if (locks.length > 0) {
sb.append("\n\tNumber of locked synchronizers = " + locks.length);
sb.append('\n');
for (LockInfo li : locks) {
sb.append("\t- " + li);
sb.append('\n');
}
}
sb.append('\n');
return sb.toString();
}
public static <T> Collection<T> emptyList() {
return Collections.emptyList();
}
public static String jsStringEscape(String s) {
StringBuilder buf = new StringBuilder();
for( int i=0; i<s.length(); i++ ) {
char ch = s.charAt(i);
switch(ch) {
case '\'':
buf.append("\\'");
break;
case '\\':
buf.append("\\\\");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(ch);
}
}
return buf.toString();
}
/**
* Converts "abc" to "Abc".
*/
public static String capitalize(String s) {
if(s==null || s.length()==0) return s;
return Character.toUpperCase(s.charAt(0))+s.substring(1);
}
public static String getVersion() {
return Jenkins.VERSION;
}
/**
* Resoruce path prefix.
*/
public static String getResourcePath() {
return Jenkins.RESOURCE_PATH;
}
public static String getViewResource(Object it, String path) {
Class clazz = it.getClass();
if(it instanceof Class)
clazz = (Class)it;
if(it instanceof Descriptor)
clazz = ((Descriptor)it).clazz;
StringBuilder buf = new StringBuilder(Stapler.getCurrentRequest().getContextPath());
buf.append(Jenkins.VIEW_RESOURCE_PATH).append('/');
buf.append(clazz.getName().replace('.','/').replace('$','/'));
buf.append('/').append(path);
return buf.toString();
}
public static boolean hasView(Object it, String path) throws IOException {
if(it==null) return false;
return Stapler.getCurrentRequest().getView(it,path)!=null;
}
/**
* Can be used to check a checkbox by default.
* Used from views like {@code h.defaultToTrue(scm.useUpdate)}.
* The expression will evaluate to true if scm is null.
*/
public static boolean defaultToTrue(Boolean b) {
if(b==null) return true;
return b;
}
/**
* If the value exists, return that value. Otherwise return the default value.
* <p>
* Starting 1.294, JEXL supports the elvis operator "x?:y" that supercedes this.
*
* @since 1.150
*/
public static <T> T defaulted(T value, T defaultValue) {
return value!=null ? value : defaultValue;
}
public static String printThrowable(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
/**
* Counts the number of rows needed for textarea to fit the content.
* Minimum 5 rows.
*/
public static int determineRows(String s) {
if(s==null) return 5;
return Math.max(5,LINE_END.split(s).length);
}
/**
* Converts the Hudson build status to CruiseControl build status,
* which is either Success, Failure, Exception, or Unknown.
*/
public static String toCCStatus(Item i) {
if (i instanceof Job) {
Job j = (Job) i;
switch (j.getIconColor().noAnime()) {
case ABORTED:
case RED:
case YELLOW:
return "Failure";
case BLUE:
return "Success";
case DISABLED:
case GREY:
return "Unknown";
}
}
return "Unknown";
}
private static final Pattern LINE_END = Pattern.compile("\r?\n");
/**
* Checks if the current user is anonymous.
*/
public static boolean isAnonymous() {
return Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken;
}
/**
* When called from within JEXL expression evaluation,
* this method returns the current {@link JellyContext} used
* to evaluate the script.
*
* @since 1.164
*/
public static JellyContext getCurrentJellyContext() {
JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get();
assert context!=null;
return context;
}
/**
* Evaluate a Jelly script and return output as a String.
*
* @since 1.267
*/
public static String runScript(Script script) throws JellyTagException {
StringWriter out = new StringWriter();
script.run(getCurrentJellyContext(), XMLOutput.createXMLOutput(out));
return out.toString();
}
/**
* Returns a sub-list if the given list is bigger than the specified 'maxSize'
*/
public static <T> List<T> subList(List<T> base, int maxSize) {
if(maxSize<base.size())
return base.subList(0,maxSize);
else
return base;
}
/**
* Combine path components via '/' while handling leading/trailing '/' to avoid duplicates.
*/
public static String joinPath(String... components) {
StringBuilder buf = new StringBuilder();
for (String s : components) {
if (s.length()==0) continue;
if (buf.length()>0) {
if (buf.charAt(buf.length()-1)!='/')
buf.append('/');
if (s.charAt(0)=='/') s=s.substring(1);
}
buf.append(s);
}
return buf.toString();
}
/**
* Computes the hyperlink to actions, to handle the situation when the {@link Action#getUrlName()}
* returns absolute URL.
*/
public static String getActionUrl(String itUrl,Action action) {
String urlName = action.getUrlName();
if(urlName==null) return null; // to avoid NPE and fail to render the whole page
try {
if (new URI(urlName).isAbsolute()) {
return urlName;
}
} catch (URISyntaxException x) {
Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x});
return null;
}
if(urlName.startsWith("/"))
return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName);
else
// relative URL name
return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName);
}
/**
* Escapes the character unsafe for e-mail address.
* See http://en.wikipedia.org/wiki/E-mail_address for the details,
* but here the vocabulary is even more restricted.
*/
public static String toEmailSafeString(String projectName) {
// TODO: escape non-ASCII characters
StringBuilder buf = new StringBuilder(projectName.length());
for( int i=0; i<projectName.length(); i++ ) {
char ch = projectName.charAt(i);
if(('a'<=ch && ch<='z')
|| ('z'<=ch && ch<='Z')
|| ('0'<=ch && ch<='9')
|| "-_.".indexOf(ch)>=0)
buf.append(ch);
else
buf.append('_'); // escape
}
return projectName;
}
public String getSystemProperty(String key) {
return System.getProperty(key);
}
/**
* Obtains the host name of the Hudson server that clients can use to talk back to.
* <p>
* This is primarily used in <tt>slave-agent.jnlp.jelly</tt> to specify the destination
* that the slaves talk to.
*/
public String getServerName() {
// Try to infer this from the configured root URL.
// This makes it work correctly when Hudson runs behind a reverse proxy.
String url = Jenkins.getInstance().getRootUrl();
try {
if(url!=null) {
String host = new URL(url).getHost();
if(host!=null)
return host;
}
} catch (MalformedURLException e) {
// fall back to HTTP request
}
return Stapler.getCurrentRequest().getServerName();
}
/**
* Determines the form validation check URL. See textbox.jelly
*/
public String getCheckUrl(String userDefined, Object descriptor, String field) {
if(userDefined!=null || field==null) return userDefined;
if (descriptor instanceof Descriptor) {
Descriptor d = (Descriptor) descriptor;
return d.getCheckUrl(field);
}
return null;
}
/**
* If the given href link is matching the current page, return true.
*
* Used in <tt>task.jelly</tt> to decide if the page should be highlighted.
*/
public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException {
String url = Stapler.getCurrentRequest().getRequestURL().toString();
if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/");
url = URLDecoder.decode(url,"UTF-8");
href = URLDecoder.decode(href,"UTF-8");
if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
if (href.endsWith("/")) href = href.substring(0, href.length() - 1);
return url.endsWith(href);
}
public <T> List<T> singletonList(T t) {
return Collections.singletonList(t);
}
/**
* Gets all the {@link PageDecorator}s.
*/
public static List<PageDecorator> getPageDecorators() {
// this method may be called to render start up errors, at which point Hudson doesn't exist yet. see HUDSON-3608
if(Jenkins.getInstance()==null) return Collections.emptyList();
return PageDecorator.all();
}
public static List<Descriptor<Cloud>> getCloudDescriptors() {
return Cloud.all();
}
/**
* Prepend a prefix only when there's the specified body.
*/
public String prepend(String prefix, String body) {
if(body!=null && body.length()>0)
return prefix+body;
return body;
}
public static List<Descriptor<CrumbIssuer>> getCrumbIssuerDescriptors() {
return CrumbIssuer.all();
}
public static String getCrumb(StaplerRequest req) {
Jenkins h = Jenkins.getInstance();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getCrumb(req) : "";
}
public static String getCrumbRequestField() {
Jenkins h = Jenkins.getInstance();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : "";
}
public static Date getCurrentTime() {
return new Date();
}
public static Locale getCurrentLocale() {
Locale locale=null;
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
locale = req.getLocale();
if(locale==null)
locale = Locale.getDefault();
return locale;
}
/**
* Generate a series of <script> tags to include <tt>script.js</tt>
* from {@link ConsoleAnnotatorFactory}s and {@link ConsoleAnnotationDescriptor}s.
*/
public static String generateConsoleAnnotationScriptAndStylesheet() {
String cp = Stapler.getCurrentRequest().getContextPath();
StringBuilder buf = new StringBuilder();
for (ConsoleAnnotatorFactory f : ConsoleAnnotatorFactory.all()) {
String path = cp + "/extensionList/" + ConsoleAnnotatorFactory.class.getName() + "/" + f.getClass().getName();
if (f.hasScript())
buf.append("<script src='"+path+"/script.js'></script>");
if (f.hasStylesheet())
buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />");
}
for (ConsoleAnnotationDescriptor d : ConsoleAnnotationDescriptor.all()) {
String path = cp+"/descriptor/"+d.clazz.getName();
if (d.hasScript())
buf.append("<script src='"+path+"/script.js'></script>");
if (d.hasStylesheet())
buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />");
}
return buf.toString();
}
/**
* Work around for bug 6935026.
*/
public List<String> getLoggerNames() {
while (true) {
try {
List<String> r = new ArrayList<String>();
Enumeration<String> e = LogManager.getLogManager().getLoggerNames();
while (e.hasMoreElements())
r.add(e.nextElement());
return r;
} catch (ConcurrentModificationException e) {
// retry
}
}
}
/**
* Used by <f:password/> so that we send an encrypted value to the client.
*/
public String getPasswordValue(Object o) {
if (o==null) return null;
if (o instanceof Secret) return ((Secret)o).getEncryptedValue();
return o.toString();
}
public List filterDescriptors(Object context, Iterable descriptors) {
return DescriptorVisibilityFilter.apply(context,descriptors);
}
/**
* Returns true if we are running unit tests.
*/
public static boolean getIsUnitTest() {
return Main.isUnitTest;
}
/**
* Returns {@code true} if the {@link Run#ARTIFACTS} permission is enabled,
* {@code false} otherwise.
*
* <p>When the {@link Run#ARTIFACTS} permission is not turned on using the
* {@code hudson.security.ArtifactsPermission} system property, this
* permission must not be considered to be set to {@code false} for every
* user. It must rather be like if the permission doesn't exist at all
* (which means that every user has to have an access to the artifacts but
* the permission can't be configured in the security screen). Got it?</p>
*/
public static boolean isArtifactsPermissionEnabled() {
return Boolean.getBoolean("hudson.security.ArtifactsPermission");
}
/**
* Returns {@code true} if the {@link Item#WIPEOUT} permission is enabled,
* {@code false} otherwise.
*
* <p>The "Wipe Out Workspace" action available on jobs is controlled by the
* {@link Item#BUILD} permission. For some specific projects, however, it is
* not acceptable to let users have this possibility, even it they can
* trigger builds. As such, when enabling the {@code hudson.security.WipeOutPermission}
* system property, a new "WipeOut" permission will allow to have greater
* control on the "Wipe Out Workspace" action.</p>
*/
public static boolean isWipeOutPermissionEnabled() {
return Boolean.getBoolean("hudson.security.WipeOutPermission");
}
public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) {
return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context,attributesToCapture));
}
public static String getCurrentDescriptorByNameUrl() {
return Descriptor.getCurrentDescriptorByNameUrl();
}
public static String setCurrentDescriptorByNameUrl(String value) {
String o = getCurrentDescriptorByNameUrl();
Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", value);
return o;
}
public static void restoreCurrentDescriptorByNameUrl(String old) {
Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", old);
}
public static List<String> getRequestHeaders(String name) {
List<String> r = new ArrayList<String>();
Enumeration e = Stapler.getCurrentRequest().getHeaders(name);
while (e.hasMoreElements()) {
r.add(e.nextElement().toString());
}
return r;
}
/**
* Used for arguments to internationalized expressions to avoid escape
*/
public static Object rawHtml(Object o) {
return o==null ? null : new RawHtmlArgument(o);
}
public static ArrayList<CLICommand> getCLICommands() {
ArrayList<CLICommand> all = new ArrayList<CLICommand>(CLICommand.all());
Collections.sort(all, new Comparator<CLICommand>() {
public int compare(CLICommand cliCommand, CLICommand cliCommand1) {
return cliCommand.getName().compareTo(cliCommand1.getName());
}
});
return all;
}
/**
* Returns an avatar image URL for the specified user and preferred image size
* @param user the user
* @param avatarSize the preferred size of the avatar image
* @return a URL string
* @since 1.433
*/
public static String getAvatar(User user, String avatarSize) {
return UserAvatarResolver.resolve(user, avatarSize);
}
/**
* @deprecated as of 1.451
* Use {@link #getAvatar}
*/
public String getUserAvatar(User user, String avatarSize) {
return getAvatar(user,avatarSize);
}
/**
* Returns human readable information about file size
*
* @param file size in bytes
* @return file size in appropriate unit
*/
public static String humanReadableByteSize(long size){
String measure = "B";
if(size < 1024){
return size + " " + measure;
}
Double number = new Double(size);
if(number>=1024){
number = number/1024;
measure = "KB";
if(number>=1024){
number = number/1024;
measure = "MB";
if(number>=1024){
number=number/1024;
measure = "GB";
}
}
}
DecimalFormat format = new DecimalFormat("#0.00");
return format.format(number) + " " + measure;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_2097_0 |
crossvul-java_data_bad_2097_0 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Yahoo! Inc., Stephen Connolly, Tom Huybrechts, Alan Harder, Manufacture
* Francaise des Pneumatiques Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import hudson.cli.CLICommand;
import hudson.console.ConsoleAnnotationDescriptor;
import hudson.console.ConsoleAnnotatorFactory;
import hudson.model.*;
import hudson.model.ParameterDefinition.ParameterDescriptor;
import hudson.search.SearchableModelObject;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.GlobalSecurityConfiguration;
import hudson.security.Permission;
import hudson.security.SecurityRealm;
import hudson.security.captcha.CaptchaSupport;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.tasks.UserAvatarResolver;
import hudson.util.Area;
import hudson.util.Iterators;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.Secret;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.RenderOnDemandClosure;
import jenkins.model.GlobalConfiguration;
import jenkins.model.GlobalConfigurationCategory;
import jenkins.model.GlobalConfigurationCategory.Unclassified;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithContextMenu;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.jexl.parser.ASTSizeFunction;
import org.apache.commons.jexl.util.Introspector;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.jvnet.tiger_types.Types;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgument;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* Utility functions used in views.
*
* <p>
* An instance of this class is created for each request and made accessible
* from view pages via the variable 'h' (h stands for Hudson.)
*
* @author Kohsuke Kawaguchi
*/
public class Functions {
private static volatile int globalIota = 0;
private int iota;
public Functions() {
iota = globalIota;
// concurrent requests can use the same ID --- we are just trying to
// prevent the same user from seeing the same ID repeatedly.
globalIota+=1000;
}
/**
* Generates an unique ID.
*/
public String generateId() {
return "id"+iota++;
}
public static boolean isModel(Object o) {
return o instanceof ModelObject;
}
public static boolean isModelWithContextMenu(Object o) {
return o instanceof ModelObjectWithContextMenu;
}
public static String xsDate(Calendar cal) {
return Util.XS_DATETIME_FORMATTER.format(cal.getTime());
}
public static String rfc822Date(Calendar cal) {
return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime());
}
public static void initPageVariables(JellyContext context) {
String rootURL = Stapler.getCurrentRequest().getContextPath();
Functions h = new Functions();
context.setVariable("h", h);
// The path starts with a "/" character but does not end with a "/" character.
context.setVariable("rootURL", rootURL);
/*
load static resources from the path dedicated to a specific version.
This "/static/VERSION/abc/def.ghi" path is interpreted by stapler to be
the same thing as "/abc/def.ghi", but this avoids the stale cache
problem when the user upgrades to new Jenkins. Stapler also sets a long
future expiration dates for such static resources.
see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML
*/
context.setVariable("resURL",rootURL+getResourcePath());
context.setVariable("imagesURL",rootURL+getResourcePath()+"/images");
}
/**
* Given {@code c=MyList (extends ArrayList<Foo>), base=List}, compute the parameterization of 'base'
* that's assignable from 'c' (in this case {@code List<Foo>}), and return its n-th type parameter
* (n=0 would return {@code Foo}).
*
* <p>
* This method is useful for doing type arithmetic.
*
* @throws AssertionError
* if c' is not parameterized.
*/
public static <B> Class getTypeParameter(Class<? extends B> c, Class<B> base, int n) {
Type parameterization = Types.getBaseClass(c,base);
if (parameterization instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) parameterization;
return Types.erasure(Types.getTypeArgument(pt,n));
} else {
throw new AssertionError(c+" doesn't properly parameterize "+base);
}
}
public JDK.DescriptorImpl getJDKDescriptor() {
return Jenkins.getInstance().getDescriptorByType(JDK.DescriptorImpl.class);
}
/**
* Prints the integer as a string that represents difference,
* like "-5", "+/-0", "+3".
*/
public static String getDiffString(int i) {
if(i==0) return "\u00B10"; // +/-0
String s = Integer.toString(i);
if(i>0) return "+"+s;
else return s;
}
/**
* {@link #getDiffString(int)} that doesn't show anything for +/-0
*/
public static String getDiffString2(int i) {
if(i==0) return "";
String s = Integer.toString(i);
if(i>0) return "+"+s;
else return s;
}
/**
* {@link #getDiffString2(int)} that puts the result into prefix and suffix
* if there's something to print
*/
public static String getDiffString2(String prefix, int i, String suffix) {
if(i==0) return "";
String s = Integer.toString(i);
if(i>0) return prefix+"+"+s+suffix;
else return prefix+s+suffix;
}
/**
* Adds the proper suffix.
*/
public static String addSuffix(int n, String singular, String plural) {
StringBuilder buf = new StringBuilder();
buf.append(n).append(' ');
if(n==1)
buf.append(singular);
else
buf.append(plural);
return buf.toString();
}
public static RunUrl decompose(StaplerRequest req) {
List<Ancestor> ancestors = req.getAncestors();
// find the first and last Run instances
Ancestor f=null,l=null;
for (Ancestor anc : ancestors) {
if(anc.getObject() instanceof Run) {
if(f==null) f=anc;
l=anc;
}
}
if(l==null) return null; // there was no Run object
String head = f.getPrev().getUrl()+'/';
String base = l.getUrl();
String reqUri = req.getOriginalRequestURI();
// Find "rest" or URI by removing N path components.
// Not using reqUri.substring(f.getUrl().length()) to avoid mismatches due to
// url-encoding or extra slashes. Former may occur in Tomcat (despite the spec saying
// this string is not decoded, Tomcat apparently decodes this string. You see ' '
// instead of '%20', which is what the browser has sent), latter may occur in some
// proxy or URL-rewriting setups where extra slashes are inadvertently added.
String furl = f.getUrl();
int slashCount = 0;
// Count components in ancestor URL
for (int i = furl.indexOf('/'); i >= 0; i = furl.indexOf('/', i + 1)) slashCount++;
// Remove that many from request URL, ignoring extra slashes
String rest = reqUri.replaceFirst("(?:/+[^/]*){" + slashCount + "}", "");
return new RunUrl( (Run) f.getObject(), head, base, rest);
}
/**
* If we know the user's screen resolution, return it. Otherwise null.
* @since 1.213
*/
public static Area getScreenResolution() {
Cookie res = Functions.getCookie(Stapler.getCurrentRequest(),"screenResolution");
if(res!=null)
return Area.parse(res.getValue());
return null;
}
/**
* URL decomposed for easier computation of relevant URLs.
*
* <p>
* The decomposed URL will be of the form:
* <pre>
* aaaaaa/524/bbbbb/cccc
* -head-| N |---rest---
* ----- base -----|
* </pre>
*
* <p>
* The head portion is the part of the URL from the {@link jenkins.model.Jenkins}
* object to the first {@link Run} subtype. When "next/prev build"
* is chosen, this part remains intact.
*
* <p>
* The <tt>524</tt> is the path from {@link Job} to {@link Run}.
*
* <p>
* The <tt>bbb</tt> portion is the path after that till the last
* {@link Run} subtype. The <tt>ccc</tt> portion is the part
* after that.
*/
public static final class RunUrl {
private final String head, base, rest;
private final Run run;
public RunUrl(Run run, String head, String base, String rest) {
this.run = run;
this.head = head;
this.base = base;
this.rest = rest;
}
public String getBaseUrl() {
return base;
}
/**
* Returns the same page in the next build.
*/
public String getNextBuildUrl() {
return getUrl(run.getNextBuild());
}
/**
* Returns the same page in the previous build.
*/
public String getPreviousBuildUrl() {
return getUrl(run.getPreviousBuild());
}
private String getUrl(Run n) {
if(n ==null)
return null;
else {
return head+n.getNumber()+rest;
}
}
}
public static Node.Mode[] getNodeModes() {
return Node.Mode.values();
}
public static String getProjectListString(List<Project> projects) {
return Items.toNameList(projects);
}
/**
* @deprecated as of 1.294
* JEXL now supports the real ternary operator "x?y:z", so this work around
* is no longer necessary.
*/
public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) {
return cond ? thenValue : elseValue;
}
public static String appendIfNotNull(String text, String suffix, String nullText) {
return text == null ? nullText : text + suffix;
}
public static Map getSystemProperties() {
return new TreeMap<Object,Object>(System.getProperties());
}
public static Map getEnvVars() {
return new TreeMap<String,String>(EnvVars.masterEnvVars);
}
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
public static List<LogRecord> getLogRecords() {
return Jenkins.logRecords;
}
public static String printLogRecord(LogRecord r) {
return formatter.format(r);
}
public static Cookie getCookie(HttpServletRequest req,String name) {
Cookie[] cookies = req.getCookies();
if(cookies!=null) {
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
public static String getCookie(HttpServletRequest req,String name, String defaultValue) {
Cookie c = getCookie(req, name);
if(c==null || c.getValue()==null) return defaultValue;
return c.getValue();
}
/**
* Gets the suffix to use for YUI JavaScript.
*/
public static String getYuiSuffix() {
return DEBUG_YUI ? "debug" : "min";
}
/**
* Set to true if you need to use the debug version of YUI.
*/
public static boolean DEBUG_YUI = Boolean.getBoolean("debug.YUI");
/**
* Creates a sub map by using the given range (both ends inclusive).
*/
public static <V> SortedMap<Integer,V> filter(SortedMap<Integer,V> map, String from, String to) {
if(from==null && to==null) return map;
if(to==null)
return map.headMap(Integer.parseInt(from)-1);
if(from==null)
return map.tailMap(Integer.parseInt(to));
return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1);
}
private static final SimpleFormatter formatter = new SimpleFormatter();
/**
* Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
*
* @param noAutoRefresh
* On certain pages, like a page with forms, will have annoying interference
* with auto refresh. On those pages, disable auto-refresh.
*/
public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response, boolean noAutoRefresh) {
if(noAutoRefresh)
return;
String param = request.getParameter("auto_refresh");
boolean refresh = isAutoRefresh(request);
if (param != null) {
refresh = Boolean.parseBoolean(param);
Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh));
// Need to set path or it will not stick from e.g. a project page to the dashboard.
// Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
// to avoid conflicts with any other web apps that might be on the same machine.
c.setPath("/");
c.setMaxAge(60*60*24*30); // persist it roughly for a month
response.addCookie(c);
}
if (refresh) {
response.addHeader("Refresh", System.getProperty("hudson.Functions.autoRefreshSeconds", "10"));
}
}
public static boolean isAutoRefresh(HttpServletRequest request) {
String param = request.getParameter("auto_refresh");
if (param != null) {
return Boolean.parseBoolean(param);
}
Cookie[] cookies = request.getCookies();
if(cookies==null)
return false; // when API design messes it up, we all suffer
for (Cookie c : cookies) {
if (c.getName().equals("hudson_auto_refresh")) {
return Boolean.parseBoolean(c.getValue());
}
}
return false;
}
/**
* Finds the given object in the ancestor list and returns its URL.
* This is used to determine the "current" URL assigned to the given object,
* so that one can compute relative URLs from it.
*/
public static String getNearestAncestorUrl(StaplerRequest req,Object it) {
List list = req.getAncestors();
for( int i=list.size()-1; i>=0; i-- ) {
Ancestor anc = (Ancestor) list.get(i);
if(anc.getObject()==it)
return anc.getUrl();
}
return null;
}
/**
* Finds the inner-most {@link SearchableModelObject} in scope.
*/
public static String getSearchURL() {
List list = Stapler.getCurrentRequest().getAncestors();
for( int i=list.size()-1; i>=0; i-- ) {
Ancestor anc = (Ancestor) list.get(i);
if(anc.getObject() instanceof SearchableModelObject)
return anc.getUrl()+"/search/";
}
return null;
}
public static String appendSpaceIfNotNull(String n) {
if(n==null) return null;
else return n+' ';
}
/**
* One nbsp per 10 pixels in given size, which may be a plain number or "NxN"
* (like an iconSize). Useful in a sortable table heading.
*/
public static String nbspIndent(String size) {
int i = size.indexOf('x');
i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10;
StringBuilder buf = new StringBuilder(30);
for (int j = 0; j < i; j++)
buf.append(" ");
return buf.toString();
}
public static String getWin32ErrorMessage(IOException e) {
return Util.getWin32ErrorMessage(e);
}
public static boolean isMultiline(String s) {
if(s==null) return false;
return s.indexOf('\r')>=0 || s.indexOf('\n')>=0;
}
public static String encode(String s) {
return Util.encode(s);
}
public static String escape(String s) {
return Util.escape(s);
}
public static String xmlEscape(String s) {
return Util.xmlEscape(s);
}
public static String xmlUnescape(String s) {
return s.replace("<","<").replace(">",">").replace("&","&");
}
public static String htmlAttributeEscape(String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='<')
buf.append("<");
else
if(ch=='>')
buf.append(">");
else
if(ch=='&')
buf.append("&");
else
if(ch=='"')
buf.append(""");
else
if(ch=='\'')
buf.append("'");
else
buf.append(ch);
}
return buf.toString();
}
public static void checkPermission(Permission permission) throws IOException, ServletException {
checkPermission(Jenkins.getInstance(),permission);
}
public static void checkPermission(AccessControlled object, Permission permission) throws IOException, ServletException {
if (permission != null) {
object.checkPermission(permission);
}
}
/**
* This version is so that the 'checkPermission' on <tt>layout.jelly</tt>
* degrades gracefully if "it" is not an {@link AccessControlled} object.
* Otherwise it will perform no check and that problem is hard to notice.
*/
public static void checkPermission(Object object, Permission permission) throws IOException, ServletException {
if (permission == null)
return;
if (object instanceof AccessControlled)
checkPermission((AccessControlled) object,permission);
else {
List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors();
for(Ancestor anc : Iterators.reverse(ancs)) {
Object o = anc.getObject();
if (o instanceof AccessControlled) {
checkPermission((AccessControlled) o,permission);
return;
}
}
checkPermission(Jenkins.getInstance(),permission);
}
}
/**
* Returns true if the current user has the given permission.
*
* @param permission
* If null, returns true. This defaulting is convenient in making the use of this method terse.
*/
public static boolean hasPermission(Permission permission) throws IOException, ServletException {
return hasPermission(Jenkins.getInstance(),permission);
}
/**
* This version is so that the 'hasPermission' can degrade gracefully
* if "it" is not an {@link AccessControlled} object.
*/
public static boolean hasPermission(Object object, Permission permission) throws IOException, ServletException {
if (permission == null)
return true;
if (object instanceof AccessControlled)
return ((AccessControlled)object).hasPermission(permission);
else {
List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors();
for(Ancestor anc : Iterators.reverse(ancs)) {
Object o = anc.getObject();
if (o instanceof AccessControlled) {
return ((AccessControlled)o).hasPermission(permission);
}
}
return Jenkins.getInstance().hasPermission(permission);
}
}
public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, ServletException {
// this is legacy --- all views should be eventually converted to
// the permission based model.
if(required!=null && !Hudson.adminCheck(req, rsp)) {
// check failed. commit the FORBIDDEN response, then abort.
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.getOutputStream().close();
throw new ServletException("Unauthorized access");
}
// make sure the user owns the necessary permission to access this page.
if(permission!=null)
checkPermission(permission);
}
/**
* Infers the hudson installation URL from the given request.
*/
public static String inferHudsonURL(StaplerRequest req) {
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl !=null)
// prefer the one explicitly configured, to work with load-balancer, frontend, etc.
return rootUrl;
StringBuilder buf = new StringBuilder();
buf.append(req.getScheme()).append("://");
buf.append(req.getServerName());
if(! (req.getScheme().equals("http") && req.getLocalPort()==80 || req.getScheme().equals("https") && req.getLocalPort()==443))
buf.append(':').append(req.getLocalPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Returns the link to be displayed in the footer of the UI.
*/
public static String getFooterURL() {
if(footerURL == null) {
footerURL = System.getProperty("hudson.footerURL");
if(StringUtils.isBlank(footerURL)) {
footerURL = "http://jenkins-ci.org/";
}
}
return footerURL;
}
private static String footerURL = null;
public static List<JobPropertyDescriptor> getJobPropertyDescriptors(Class<? extends Job> clazz) {
return JobPropertyDescriptor.getPropertyDescriptors(clazz);
}
public static List<Descriptor<BuildWrapper>> getBuildWrapperDescriptors(AbstractProject<?,?> project) {
return BuildWrappers.getFor(project);
}
public static List<Descriptor<SecurityRealm>> getSecurityRealmDescriptors() {
return SecurityRealm.all();
}
public static List<Descriptor<AuthorizationStrategy>> getAuthorizationStrategyDescriptors() {
return AuthorizationStrategy.all();
}
public static List<Descriptor<Builder>> getBuilderDescriptors(AbstractProject<?,?> project) {
return BuildStepDescriptor.filter(Builder.all(), project.getClass());
}
public static List<Descriptor<Publisher>> getPublisherDescriptors(AbstractProject<?,?> project) {
return BuildStepDescriptor.filter(Publisher.all(), project.getClass());
}
public static List<SCMDescriptor<?>> getSCMDescriptors(AbstractProject<?,?> project) {
return SCM._for(project);
}
public static List<Descriptor<ComputerLauncher>> getComputerLauncherDescriptors() {
return Jenkins.getInstance().<ComputerLauncher,Descriptor<ComputerLauncher>>getDescriptorList(ComputerLauncher.class);
}
public static List<Descriptor<RetentionStrategy<?>>> getRetentionStrategyDescriptors() {
return RetentionStrategy.all();
}
public static List<ParameterDescriptor> getParameterDescriptors() {
return ParameterDefinition.all();
}
public static List<Descriptor<CaptchaSupport>> getCaptchaSupportDescriptors() {
return CaptchaSupport.all();
}
public static List<Descriptor<ViewsTabBar>> getViewsTabBarDescriptors() {
return ViewsTabBar.all();
}
public static List<Descriptor<MyViewsTabBar>> getMyViewsTabBarDescriptors() {
return MyViewsTabBar.all();
}
public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) {
List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>();
Collection<NodePropertyDescriptor> list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : list) {
if (npd.isApplicable(clazz)) {
result.add(npd);
}
}
return result;
}
/**
* Gets all the descriptors sorted by their inheritance tree of {@link Describable}
* so that descriptors of similar types come nearby.
*
* <p>
* We sort them by {@link Extension#ordinal()} but only for {@link GlobalConfiguration}s,
* as the value is normally used to compare similar kinds of extensions, and we needed
* {@link GlobalConfiguration}s to be able to position themselves in a layer above.
* This however creates some asymmetry between regular {@link Descriptor}s and {@link GlobalConfiguration}s.
* Perhaps it is better to introduce another annotation element? But then,
* extensions shouldn't normally concern themselves about ordering too much, and the only reason
* we needed this for {@link GlobalConfiguration}s are for backward compatibility.
*
* @param predicate
* Filter the descriptors based on {@link GlobalConfigurationCategory}
* @since 1.494
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig(Predicate<GlobalConfigurationCategory> predicate) {
ExtensionList<Descriptor> exts = Jenkins.getInstance().getExtensionList(Descriptor.class);
List<Tag> r = new ArrayList<Tag>(exts.size());
for (ExtensionComponent<Descriptor> c : exts.getComponents()) {
Descriptor d = c.getInstance();
if (d.getGlobalConfigPage()==null) continue;
if (d instanceof GlobalConfiguration) {
if (predicate.apply(((GlobalConfiguration)d).getCategory()))
r.add(new Tag(c.ordinal(), d));
} else {
if (predicate.apply(GlobalConfigurationCategory.get(Unclassified.class)))
r.add(new Tag(0, d));
}
}
Collections.sort(r);
List<Descriptor> answer = new ArrayList<Descriptor>(r.size());
for (Tag d : r) answer.add(d.d);
return DescriptorVisibilityFilter.apply(Jenkins.getInstance(),answer);
}
/**
* Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but with a constant truth predicate, to include all descriptors.
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig() {
return getSortedDescriptorsForGlobalConfig(Predicates.<GlobalConfigurationCategory>alwaysTrue());
}
/**
* @deprecated This is rather meaningless.
*/
@Deprecated
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigNoSecurity() {
return getSortedDescriptorsForGlobalConfig(Predicates.not(GlobalSecurityConfiguration.FILTER));
}
/**
* Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but for unclassified descriptors only.
* @since 1.506
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassified() {
return getSortedDescriptorsForGlobalConfig(new Predicate<GlobalConfigurationCategory>() {
public boolean apply(GlobalConfigurationCategory cat) {
return cat instanceof GlobalConfigurationCategory.Unclassified;
}
});
}
private static class Tag implements Comparable<Tag> {
double ordinal;
String hierarchy;
Descriptor d;
Tag(double ordinal, Descriptor d) {
this.ordinal = ordinal;
this.d = d;
this.hierarchy = buildSuperclassHierarchy(d.clazz, new StringBuilder()).toString();
}
private StringBuilder buildSuperclassHierarchy(Class c, StringBuilder buf) {
Class sc = c.getSuperclass();
if (sc!=null) buildSuperclassHierarchy(sc,buf).append(':');
return buf.append(c.getName());
}
public int compareTo(Tag that) {
int r = Double.compare(this.ordinal, that.ordinal);
if (r!=0) return -r; // descending for ordinal
return this.hierarchy.compareTo(that.hierarchy);
}
}
/**
* Computes the path to the icon of the given action
* from the context path.
*/
public static String getIconFilePath(Action a) {
String name = a.getIconFileName();
if (name==null) return null;
if (name.startsWith("/"))
return name.substring(1);
else
return "images/24x24/"+name;
}
/**
* Works like JSTL build-in size(x) function,
* but handle null gracefully.
*/
public static int size2(Object o) throws Exception {
if(o==null) return 0;
return ASTSizeFunction.sizeOf(o,Introspector.getUberspect());
}
/**
* Computes the relative path from the current page to the given item.
*/
public static String getRelativeLinkTo(Item p) {
Map<Object,String> ancestors = new HashMap<Object,String>();
View view=null;
StaplerRequest request = Stapler.getCurrentRequest();
for( Ancestor a : request.getAncestors() ) {
ancestors.put(a.getObject(),a.getRelativePath());
if(a.getObject() instanceof View)
view = (View) a.getObject();
}
String path = ancestors.get(p);
if(path!=null) return path;
Item i=p;
String url = "";
while(true) {
ItemGroup ig = i.getParent();
url = i.getShortUrl()+url;
if(ig== Jenkins.getInstance()) {
assert i instanceof TopLevelItem;
if(view!=null && view.contains((TopLevelItem)i)) {
// if p and the current page belongs to the same view, then return a relative path
return ancestors.get(view)+'/'+url;
} else {
// otherwise return a path from the root Hudson
return request.getContextPath()+'/'+p.getUrl();
}
}
path = ancestors.get(ig);
if(path!=null) return path+'/'+url;
assert ig instanceof Item; // if not, ig must have been the Hudson instance
i = (Item) ig;
}
}
public static Map<Thread,StackTraceElement[]> dumpAllThreads() {
Map<Thread,StackTraceElement[]> sorted = new TreeMap<Thread,StackTraceElement[]>(new ThreadSorter());
sorted.putAll(Thread.getAllStackTraces());
return sorted;
}
@IgnoreJRERequirement
public static ThreadInfo[] getThreadInfos() {
ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(),mbean.isSynchronizerUsageSupported());
}
public static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) {
ThreadGroupMap sorter = new ThreadGroupMap();
Arrays.sort(list, sorter);
return sorter;
}
// Common code for sorting Threads/ThreadInfos by ThreadGroup
private static class ThreadSorterBase {
protected Map<Long,String> map = new HashMap<Long,String>();
private ThreadSorterBase() {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while (tg.getParent() != null) tg = tg.getParent();
Thread[] threads = new Thread[tg.activeCount()*2];
int threadsLen = tg.enumerate(threads, true);
for (int i = 0; i < threadsLen; i++)
map.put(threads[i].getId(), threads[i].getThreadGroup().getName());
}
protected int compare(long idA, long idB) {
String tga = map.get(idA), tgb = map.get(idB);
int result = (tga!=null?-1:0) + (tgb!=null?1:0); // Will be non-zero if only one is null
if (result==0 && tga!=null)
result = tga.compareToIgnoreCase(tgb);
return result;
}
}
public static class ThreadGroupMap extends ThreadSorterBase implements Comparator<ThreadInfo> {
/**
* @return ThreadGroup name or null if unknown
*/
public String getThreadGroup(ThreadInfo ti) {
return map.get(ti.getThreadId());
}
public int compare(ThreadInfo a, ThreadInfo b) {
int result = compare(a.getThreadId(), b.getThreadId());
if (result == 0)
result = a.getThreadName().compareToIgnoreCase(b.getThreadName());
return result;
}
}
private static class ThreadSorter extends ThreadSorterBase implements Comparator<Thread> {
public int compare(Thread a, Thread b) {
int result = compare(a.getId(), b.getId());
if (result == 0)
result = a.getName().compareToIgnoreCase(b.getName());
return result;
}
}
/**
* Are we running on JRE6 or above?
*/
@IgnoreJRERequirement
public static boolean isMustangOrAbove() {
try {
System.console();
return true;
} catch(LinkageError e) {
return false;
}
}
// ThreadInfo.toString() truncates the stack trace by first 8, so needed my own version
@IgnoreJRERequirement
public static String dumpThreadInfo(ThreadInfo ti, ThreadGroupMap map) {
String grp = map.getThreadGroup(ti);
StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"" +
" Id=" + ti.getThreadId() + " Group=" +
(grp != null ? grp : "?") + " " +
ti.getThreadState());
if (ti.getLockName() != null) {
sb.append(" on " + ti.getLockName());
}
if (ti.getLockOwnerName() != null) {
sb.append(" owned by \"" + ti.getLockOwnerName() +
"\" Id=" + ti.getLockOwnerId());
}
if (ti.isSuspended()) {
sb.append(" (suspended)");
}
if (ti.isInNative()) {
sb.append(" (in native)");
}
sb.append('\n');
StackTraceElement[] stackTrace = ti.getStackTrace();
for (int i=0; i < stackTrace.length; i++) {
StackTraceElement ste = stackTrace[i];
sb.append("\tat " + ste.toString());
sb.append('\n');
if (i == 0 && ti.getLockInfo() != null) {
Thread.State ts = ti.getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on " + ti.getLockInfo());
sb.append('\n');
break;
case WAITING:
sb.append("\t- waiting on " + ti.getLockInfo());
sb.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on " + ti.getLockInfo());
sb.append('\n');
break;
default:
}
}
for (MonitorInfo mi : ti.getLockedMonitors()) {
if (mi.getLockedStackDepth() == i) {
sb.append("\t- locked " + mi);
sb.append('\n');
}
}
}
LockInfo[] locks = ti.getLockedSynchronizers();
if (locks.length > 0) {
sb.append("\n\tNumber of locked synchronizers = " + locks.length);
sb.append('\n');
for (LockInfo li : locks) {
sb.append("\t- " + li);
sb.append('\n');
}
}
sb.append('\n');
return sb.toString();
}
public static <T> Collection<T> emptyList() {
return Collections.emptyList();
}
public static String jsStringEscape(String s) {
StringBuilder buf = new StringBuilder();
for( int i=0; i<s.length(); i++ ) {
char ch = s.charAt(i);
switch(ch) {
case '\'':
buf.append("\\'");
break;
case '\\':
buf.append("\\\\");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(ch);
}
}
return buf.toString();
}
/**
* Converts "abc" to "Abc".
*/
public static String capitalize(String s) {
if(s==null || s.length()==0) return s;
return Character.toUpperCase(s.charAt(0))+s.substring(1);
}
public static String getVersion() {
return Jenkins.VERSION;
}
/**
* Resoruce path prefix.
*/
public static String getResourcePath() {
return Jenkins.RESOURCE_PATH;
}
public static String getViewResource(Object it, String path) {
Class clazz = it.getClass();
if(it instanceof Class)
clazz = (Class)it;
if(it instanceof Descriptor)
clazz = ((Descriptor)it).clazz;
StringBuilder buf = new StringBuilder(Stapler.getCurrentRequest().getContextPath());
buf.append(Jenkins.VIEW_RESOURCE_PATH).append('/');
buf.append(clazz.getName().replace('.','/').replace('$','/'));
buf.append('/').append(path);
return buf.toString();
}
public static boolean hasView(Object it, String path) throws IOException {
if(it==null) return false;
return Stapler.getCurrentRequest().getView(it,path)!=null;
}
/**
* Can be used to check a checkbox by default.
* Used from views like {@code h.defaultToTrue(scm.useUpdate)}.
* The expression will evaluate to true if scm is null.
*/
public static boolean defaultToTrue(Boolean b) {
if(b==null) return true;
return b;
}
/**
* If the value exists, return that value. Otherwise return the default value.
* <p>
* Starting 1.294, JEXL supports the elvis operator "x?:y" that supercedes this.
*
* @since 1.150
*/
public static <T> T defaulted(T value, T defaultValue) {
return value!=null ? value : defaultValue;
}
public static String printThrowable(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
/**
* Counts the number of rows needed for textarea to fit the content.
* Minimum 5 rows.
*/
public static int determineRows(String s) {
if(s==null) return 5;
return Math.max(5,LINE_END.split(s).length);
}
/**
* Converts the Hudson build status to CruiseControl build status,
* which is either Success, Failure, Exception, or Unknown.
*/
public static String toCCStatus(Item i) {
if (i instanceof Job) {
Job j = (Job) i;
switch (j.getIconColor().noAnime()) {
case ABORTED:
case RED:
case YELLOW:
return "Failure";
case BLUE:
return "Success";
case DISABLED:
case GREY:
return "Unknown";
}
}
return "Unknown";
}
private static final Pattern LINE_END = Pattern.compile("\r?\n");
/**
* Checks if the current user is anonymous.
*/
public static boolean isAnonymous() {
return Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken;
}
/**
* When called from within JEXL expression evaluation,
* this method returns the current {@link JellyContext} used
* to evaluate the script.
*
* @since 1.164
*/
public static JellyContext getCurrentJellyContext() {
JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get();
assert context!=null;
return context;
}
/**
* Evaluate a Jelly script and return output as a String.
*
* @since 1.267
*/
public static String runScript(Script script) throws JellyTagException {
StringWriter out = new StringWriter();
script.run(getCurrentJellyContext(), XMLOutput.createXMLOutput(out));
return out.toString();
}
/**
* Returns a sub-list if the given list is bigger than the specified 'maxSize'
*/
public static <T> List<T> subList(List<T> base, int maxSize) {
if(maxSize<base.size())
return base.subList(0,maxSize);
else
return base;
}
/**
* Combine path components via '/' while handling leading/trailing '/' to avoid duplicates.
*/
public static String joinPath(String... components) {
StringBuilder buf = new StringBuilder();
for (String s : components) {
if (s.length()==0) continue;
if (buf.length()>0) {
if (buf.charAt(buf.length()-1)!='/')
buf.append('/');
if (s.charAt(0)=='/') s=s.substring(1);
}
buf.append(s);
}
return buf.toString();
}
/**
* Computes the hyperlink to actions, to handle the situation when the {@link Action#getUrlName()}
* returns absolute URL.
*/
public static String getActionUrl(String itUrl,Action action) {
String urlName = action.getUrlName();
if(urlName==null) return null; // to avoid NPE and fail to render the whole page
try {
if (new URI(urlName).isAbsolute()) {
return urlName;
}
} catch (URISyntaxException x) {
Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x});
return null;
}
if(urlName.startsWith("/"))
return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName);
else
// relative URL name
return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName);
}
/**
* Escapes the character unsafe for e-mail address.
* See http://en.wikipedia.org/wiki/E-mail_address for the details,
* but here the vocabulary is even more restricted.
*/
public static String toEmailSafeString(String projectName) {
// TODO: escape non-ASCII characters
StringBuilder buf = new StringBuilder(projectName.length());
for( int i=0; i<projectName.length(); i++ ) {
char ch = projectName.charAt(i);
if(('a'<=ch && ch<='z')
|| ('z'<=ch && ch<='Z')
|| ('0'<=ch && ch<='9')
|| "-_.".indexOf(ch)>=0)
buf.append(ch);
else
buf.append('_'); // escape
}
return projectName;
}
public String getSystemProperty(String key) {
return System.getProperty(key);
}
/**
* Obtains the host name of the Hudson server that clients can use to talk back to.
* <p>
* This is primarily used in <tt>slave-agent.jnlp.jelly</tt> to specify the destination
* that the slaves talk to.
*/
public String getServerName() {
// Try to infer this from the configured root URL.
// This makes it work correctly when Hudson runs behind a reverse proxy.
String url = Jenkins.getInstance().getRootUrl();
try {
if(url!=null) {
String host = new URL(url).getHost();
if(host!=null)
return host;
}
} catch (MalformedURLException e) {
// fall back to HTTP request
}
return Stapler.getCurrentRequest().getServerName();
}
/**
* Determines the form validation check URL. See textbox.jelly
*/
public String getCheckUrl(String userDefined, Object descriptor, String field) {
if(userDefined!=null || field==null) return userDefined;
if (descriptor instanceof Descriptor) {
Descriptor d = (Descriptor) descriptor;
return d.getCheckUrl(field);
}
return null;
}
/**
* If the given href link is matching the current page, return true.
*
* Used in <tt>task.jelly</tt> to decide if the page should be highlighted.
*/
public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException {
String url = Stapler.getCurrentRequest().getRequestURL().toString();
if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/");
url = URLDecoder.decode(url,"UTF-8");
href = URLDecoder.decode(href,"UTF-8");
if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
if (href.endsWith("/")) href = href.substring(0, href.length() - 1);
return url.endsWith(href);
}
public <T> List<T> singletonList(T t) {
return Collections.singletonList(t);
}
/**
* Gets all the {@link PageDecorator}s.
*/
public static List<PageDecorator> getPageDecorators() {
// this method may be called to render start up errors, at which point Hudson doesn't exist yet. see HUDSON-3608
if(Jenkins.getInstance()==null) return Collections.emptyList();
return PageDecorator.all();
}
public static List<Descriptor<Cloud>> getCloudDescriptors() {
return Cloud.all();
}
/**
* Prepend a prefix only when there's the specified body.
*/
public String prepend(String prefix, String body) {
if(body!=null && body.length()>0)
return prefix+body;
return body;
}
public static List<Descriptor<CrumbIssuer>> getCrumbIssuerDescriptors() {
return CrumbIssuer.all();
}
public static String getCrumb(StaplerRequest req) {
Jenkins h = Jenkins.getInstance();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getCrumb(req) : "";
}
public static String getCrumbRequestField() {
Jenkins h = Jenkins.getInstance();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : "";
}
public static Date getCurrentTime() {
return new Date();
}
public static Locale getCurrentLocale() {
Locale locale=null;
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
locale = req.getLocale();
if(locale==null)
locale = Locale.getDefault();
return locale;
}
/**
* Generate a series of <script> tags to include <tt>script.js</tt>
* from {@link ConsoleAnnotatorFactory}s and {@link ConsoleAnnotationDescriptor}s.
*/
public static String generateConsoleAnnotationScriptAndStylesheet() {
String cp = Stapler.getCurrentRequest().getContextPath();
StringBuilder buf = new StringBuilder();
for (ConsoleAnnotatorFactory f : ConsoleAnnotatorFactory.all()) {
String path = cp + "/extensionList/" + ConsoleAnnotatorFactory.class.getName() + "/" + f.getClass().getName();
if (f.hasScript())
buf.append("<script src='"+path+"/script.js'></script>");
if (f.hasStylesheet())
buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />");
}
for (ConsoleAnnotationDescriptor d : ConsoleAnnotationDescriptor.all()) {
String path = cp+"/descriptor/"+d.clazz.getName();
if (d.hasScript())
buf.append("<script src='"+path+"/script.js'></script>");
if (d.hasStylesheet())
buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />");
}
return buf.toString();
}
/**
* Work around for bug 6935026.
*/
public List<String> getLoggerNames() {
while (true) {
try {
List<String> r = new ArrayList<String>();
Enumeration<String> e = LogManager.getLogManager().getLoggerNames();
while (e.hasMoreElements())
r.add(e.nextElement());
return r;
} catch (ConcurrentModificationException e) {
// retry
}
}
}
/**
* Used by <f:password/> so that we send an encrypted value to the client.
*/
public String getPasswordValue(Object o) {
if (o==null) return null;
if (o instanceof Secret) return ((Secret)o).getEncryptedValue();
return o.toString();
}
public List filterDescriptors(Object context, Iterable descriptors) {
return DescriptorVisibilityFilter.apply(context,descriptors);
}
/**
* Returns true if we are running unit tests.
*/
public static boolean getIsUnitTest() {
return Main.isUnitTest;
}
/**
* Returns {@code true} if the {@link Run#ARTIFACTS} permission is enabled,
* {@code false} otherwise.
*
* <p>When the {@link Run#ARTIFACTS} permission is not turned on using the
* {@code hudson.security.ArtifactsPermission} system property, this
* permission must not be considered to be set to {@code false} for every
* user. It must rather be like if the permission doesn't exist at all
* (which means that every user has to have an access to the artifacts but
* the permission can't be configured in the security screen). Got it?</p>
*/
public static boolean isArtifactsPermissionEnabled() {
return Boolean.getBoolean("hudson.security.ArtifactsPermission");
}
/**
* Returns {@code true} if the {@link Item#WIPEOUT} permission is enabled,
* {@code false} otherwise.
*
* <p>The "Wipe Out Workspace" action available on jobs is controlled by the
* {@link Item#BUILD} permission. For some specific projects, however, it is
* not acceptable to let users have this possibility, even it they can
* trigger builds. As such, when enabling the {@code hudson.security.WipeOutPermission}
* system property, a new "WipeOut" permission will allow to have greater
* control on the "Wipe Out Workspace" action.</p>
*/
public static boolean isWipeOutPermissionEnabled() {
return Boolean.getBoolean("hudson.security.WipeOutPermission");
}
public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) {
return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context,attributesToCapture));
}
public static String getCurrentDescriptorByNameUrl() {
return Descriptor.getCurrentDescriptorByNameUrl();
}
public static String setCurrentDescriptorByNameUrl(String value) {
String o = getCurrentDescriptorByNameUrl();
Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", value);
return o;
}
public static void restoreCurrentDescriptorByNameUrl(String old) {
Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", old);
}
public static List<String> getRequestHeaders(String name) {
List<String> r = new ArrayList<String>();
Enumeration e = Stapler.getCurrentRequest().getHeaders(name);
while (e.hasMoreElements()) {
r.add(e.nextElement().toString());
}
return r;
}
/**
* Used for arguments to internationalized expressions to avoid escape
*/
public static Object rawHtml(Object o) {
return o==null ? null : new RawHtmlArgument(o);
}
public static ArrayList<CLICommand> getCLICommands() {
ArrayList<CLICommand> all = new ArrayList<CLICommand>(CLICommand.all());
Collections.sort(all, new Comparator<CLICommand>() {
public int compare(CLICommand cliCommand, CLICommand cliCommand1) {
return cliCommand.getName().compareTo(cliCommand1.getName());
}
});
return all;
}
/**
* Returns an avatar image URL for the specified user and preferred image size
* @param user the user
* @param avatarSize the preferred size of the avatar image
* @return a URL string
* @since 1.433
*/
public static String getAvatar(User user, String avatarSize) {
return UserAvatarResolver.resolve(user, avatarSize);
}
/**
* @deprecated as of 1.451
* Use {@link #getAvatar}
*/
public String getUserAvatar(User user, String avatarSize) {
return getAvatar(user,avatarSize);
}
/**
* Returns human readable information about file size
*
* @param file size in bytes
* @return file size in appropriate unit
*/
public static String humanReadableByteSize(long size){
String measure = "B";
if(size < 1024){
return size + " " + measure;
}
Double number = new Double(size);
if(number>=1024){
number = number/1024;
measure = "KB";
if(number>=1024){
number = number/1024;
measure = "MB";
if(number>=1024){
number=number/1024;
measure = "GB";
}
}
}
DecimalFormat format = new DecimalFormat("#0.00");
return format.format(number) + " " + measure;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_2097_0 |
crossvul-java_data_good_1163_0 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.faces.context;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM;
import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.application.ResourceHandler;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.component.visit.VisitContextWrapper;
import javax.faces.component.visit.VisitHint;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import com.sun.faces.RIConstants;
import com.sun.faces.component.visit.PartialVisitContext;
import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.HtmlUtils;
import com.sun.faces.util.Util;
public class PartialViewContextImpl extends PartialViewContext {
// Log instance for this class
private static Logger LOGGER = FacesLogger.CONTEXT.getLogger();
private boolean released;
// BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD
private PartialResponseWriter partialResponseWriter;
private List<String> executeIds;
private Collection<String> renderIds;
private List<String> evalScripts;
private Boolean ajaxRequest;
private Boolean partialRequest;
private Boolean renderAll;
private FacesContext ctx;
private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER";
// ----------------------------------------------------------- Constructors
public PartialViewContextImpl(FacesContext ctx) {
this.ctx = ctx;
}
// ---------------------------------------------- Methods from PartialViewContext
/**
* @see javax.faces.context.PartialViewContext#isAjaxRequest()
*/
@Override
public boolean isAjaxRequest() {
assertNotReleased();
if (ajaxRequest == null) {
ajaxRequest = "partial/ajax".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
if (!ajaxRequest) {
ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap().
get("Faces-Request"));
}
}
return ajaxRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isPartialRequest()
*/
@Override
public boolean isPartialRequest() {
assertNotReleased();
if (partialRequest == null) {
partialRequest = isAjaxRequest() ||
"partial/process".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
}
return partialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isExecuteAll()
*/
@Override
public boolean isExecuteAll() {
assertNotReleased();
String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx);
return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute));
}
/**
* @see javax.faces.context.PartialViewContext#isRenderAll()
*/
@Override
public boolean isRenderAll() {
assertNotReleased();
if (renderAll == null) {
String render = PARTIAL_RENDER_PARAM.getValue(ctx);
renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render));
}
return renderAll;
}
/**
* @see javax.faces.context.PartialViewContext#setRenderAll(boolean)
*/
@Override
public void setRenderAll(boolean renderAll) {
this.renderAll = renderAll;
}
@Override
public boolean isResetValues() {
Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx);
return (null != value && "true".equals(value)) ? true : false;
}
@Override
public void setPartialRequest(boolean isPartialRequest) {
this.partialRequest = isPartialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#getExecuteIds()
*/
@Override
public Collection<String> getExecuteIds() {
assertNotReleased();
if (executeIds != null) {
return executeIds;
}
executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM);
// include the view parameter facet ID if there are other execute IDs
// to process
if (!executeIds.isEmpty()) {
UIViewRoot root = ctx.getViewRoot();
if (root.getFacetCount() > 0) {
if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) {
executeIds.add(0, UIViewRoot.METADATA_FACET_NAME);
}
}
}
return executeIds;
}
/**
* @see javax.faces.context.PartialViewContext#getRenderIds()
*/
@Override
public Collection<String> getRenderIds() {
assertNotReleased();
if (renderIds != null) {
return renderIds;
}
renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM);
return renderIds;
}
/**
* @see javax.faces.context.PartialViewContext#getEvalScripts()
*/
@Override
public List<String> getEvalScripts() {
assertNotReleased();
if (evalScripts == null) {
evalScripts = new ArrayList<>(1);
}
return evalScripts;
}
/**
* @see PartialViewContext#processPartial(javax.faces.event.PhaseId)
*/
@Override
public void processPartial(PhaseId phaseId) {
PartialViewContext pvc = ctx.getPartialViewContext();
Collection <String> myExecuteIds = pvc.getExecuteIds();
Collection <String> myRenderIds = pvc.getRenderIds();
UIViewRoot viewRoot = ctx.getViewRoot();
if (phaseId == PhaseId.APPLY_REQUEST_VALUES ||
phaseId == PhaseId.PROCESS_VALIDATIONS ||
phaseId == PhaseId.UPDATE_MODEL_VALUES) {
// Skip this processing if "none" is specified in the render list,
// or there were no execute phase client ids.
if (myExecuteIds == null || myExecuteIds.isEmpty()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"No execute and render identifiers specified. Skipping component processing.");
}
return;
}
try {
processComponents(viewRoot, phaseId, myExecuteIds, ctx);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO,
e.toString(),
e);
}
throw new FacesException(e);
}
// If we have just finished APPLY_REQUEST_VALUES phase, install the
// partial response writer. We want to make sure that any content
// or errors generated in the other phases are written using the
// partial response writer.
//
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ctx.setResponseWriter(writer);
}
} else if (phaseId == PhaseId.RENDER_RESPONSE) {
try {
//
// We re-enable response writing.
//
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ResponseWriter orig = ctx.getResponseWriter();
ctx.getAttributes().put(ORIGINAL_WRITER, orig);
ctx.setResponseWriter(writer);
ExternalContext exContext = ctx.getExternalContext();
exContext.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE);
exContext.addResponseHeader("Cache-Control", "no-cache");
// String encoding = writer.getCharacterEncoding( );
// if( encoding == null ) {
// encoding = "UTF-8";
// }
// writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n");
writer.startDocument();
if (isResetValues()) {
viewRoot.resetValues(ctx, myRenderIds);
}
if (isRenderAll()) {
renderAll(ctx, viewRoot);
renderState(ctx);
writer.endDocument();
return;
}
renderComponentResources(ctx, viewRoot);
// Skip this processing if "none" is specified in the render list,
// or there were no render phase client ids.
if (myRenderIds != null && !myRenderIds.isEmpty()) {
processComponents(viewRoot, phaseId, myRenderIds, ctx);
}
renderState(ctx);
renderEvalScripts(ctx);
writer.endDocument();
} catch (IOException ex) {
this.cleanupAfterView();
} catch (RuntimeException ex) {
this.cleanupAfterView();
// Throw the exception
throw ex;
}
}
}
/**
* @see javax.faces.context.PartialViewContext#getPartialResponseWriter()
*/
@Override
public PartialResponseWriter getPartialResponseWriter() {
assertNotReleased();
if (partialResponseWriter == null) {
partialResponseWriter = new DelayedInitPartialResponseWriter(this);
}
return partialResponseWriter;
}
/**
* @see javax.faces.context.PartialViewContext#release()
*/
@Override
public void release() {
released = true;
ajaxRequest = null;
renderAll = null;
partialResponseWriter = null;
executeIds = null;
renderIds = null;
evalScripts = null;
ctx = null;
partialRequest = null;
}
// -------------------------------------------------------- Private Methods
private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) {
String param = parameterName.getValue(ctx);
if (param == null) {
return new ArrayList<>();
} else {
Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
String[] pcs = Util.split(appMap, param, "[ \t]+");
return ((pcs != null && pcs.length != 0)
? new ArrayList<>(Arrays.asList(pcs))
: new ArrayList<>());
}
}
// Process the components specified in the phaseClientIds list
private void processComponents(UIComponent component, PhaseId phaseId,
Collection<String> phaseClientIds, FacesContext context) throws IOException {
// We use the tree visitor mechanism to locate the components to
// process. Create our (partial) VisitContext and the
// VisitCallback that will be invoked for each component that
// is visited. Note that we use the SKIP_UNRENDERED hint as we
// only want to visit the rendered subtree.
EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE);
VisitContextFactory visitContextFactory = (VisitContextFactory)
FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY);
VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints);
PhaseAwareVisitCallback visitCallback =
new PhaseAwareVisitCallback(ctx, phaseId);
component.visitTree(visitContext, visitCallback);
PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext);
if (partialVisitContext != null) {
if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) {
Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds();
StringBuilder builder = new StringBuilder();
for (String cur : unvisitedClientIds) {
builder.append(cur).append(" ");
}
LOGGER.log(Level.FINER,
"jsf.context.partial_visit_context_unvisited_children",
new Object[]{builder.toString()});
}
}
}
/**
* Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s.
*
* If no {@link PartialVisitContext} is found in the chain, null is returned instead.
*
* @param visitContext the visit context.
* @return the (unwrapped) partial visit context.
*/
private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) {
if (visitContext == null) {
return null;
}
if (visitContext instanceof PartialVisitContext) {
return (PartialVisitContext) visitContext;
}
if (visitContext instanceof VisitContextWrapper) {
return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped());
}
return null;
}
private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException {
// If this is a "render all via ajax" request,
// make sure to wrap the entire page in a <render> elemnt
// with the special viewStateId of VIEW_ROOT_ID. This is how the client
// JavaScript knows how to replace the entire document with
// this response.
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
if (!(viewRoot instanceof NamingContainer)) {
writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
writer.endUpdate();
}
else {
/*
* If we have a portlet request, start rendering at the view root.
*/
writer.startUpdate(viewRoot.getClientId(context));
viewRoot.encodeBegin(context);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
viewRoot.encodeEnd(context);
writer.endUpdate();
}
}
private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException {
ResourceHandler resourceHandler = context.getApplication().getResourceHandler();
PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
boolean updateStarted = false;
for (UIComponent resource : viewRoot.getComponentResources(context)) {
String name = (String) resource.getAttributes().get("name");
String library = (String) resource.getAttributes().get("library");
if (resource.getChildCount() == 0
&& resourceHandler.getRendererTypeForResourceName(name) != null
&& !resourceHandler.isResourceRendered(context, name, library))
{
if (!updateStarted) {
writer.startUpdate("javax.faces.Resource");
updateStarted = true;
}
resource.encodeAll(context);
}
}
if (updateStarted) {
writer.endUpdate();
}
}
private void renderState(FacesContext context) throws IOException {
// Get the view state and write it to the response..
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
String viewStateId = Util.getViewStateId(context);
writer.startUpdate(viewStateId);
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
writer.endUpdate();
ClientWindow window = context.getExternalContext().getClientWindow();
if (null != window) {
String clientWindowId = Util.getClientWindowId(context);
writer.startUpdate(clientWindowId);
writer.writeText(window.getId(), null);
writer.endUpdate();
}
}
private void renderEvalScripts(FacesContext context) throws IOException {
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
for (String evalScript : pvc.getEvalScripts()) {
writer.startEval();
writer.write(evalScript);
writer.endEval();
}
}
private PartialResponseWriter createPartialResponseWriter() {
ExternalContext extContext = ctx.getExternalContext();
String encoding = extContext.getRequestCharacterEncoding();
extContext.setResponseCharacterEncoding(encoding);
ResponseWriter responseWriter = null;
Writer out = null;
try {
out = extContext.getResponseOutputWriter();
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
}
if (out != null) {
UIViewRoot viewRoot = ctx.getViewRoot();
if (viewRoot != null) {
responseWriter =
ctx.getRenderKit().createResponseWriter(out,
RIConstants.TEXT_XML_CONTENT_TYPE, encoding);
} else {
RenderKitFactory factory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);
responseWriter = renderKit.createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding);
}
}
if (responseWriter instanceof PartialResponseWriter) {
return (PartialResponseWriter) responseWriter;
} else {
return new PartialResponseWriter(responseWriter);
}
}
private void cleanupAfterView() {
ResponseWriter orig = (ResponseWriter) ctx.getAttributes().
get(ORIGINAL_WRITER);
assert(null != orig);
// move aside the PartialResponseWriter
ctx.setResponseWriter(orig);
}
private void assertNotReleased() {
if (released) {
throw new IllegalStateException();
}
}
// ----------------------------------------------------------- Inner Classes
private static class PhaseAwareVisitCallback implements VisitCallback {
private PhaseId curPhase;
private FacesContext ctx;
private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) {
this.ctx = ctx;
this.curPhase = curPhase;
}
@Override
public VisitResult visit(VisitContext context, UIComponent comp) {
try {
if (curPhase == PhaseId.APPLY_REQUEST_VALUES) {
// RELEASE_PENDING handle immediate request(s)
// If the user requested an immediate request
// Make sure to set the immediate flag here.
comp.processDecodes(ctx);
} else if (curPhase == PhaseId.PROCESS_VALIDATIONS) {
comp.processValidators(ctx);
} else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) {
comp.processUpdates(ctx);
} else if (curPhase == PhaseId.RENDER_RESPONSE) {
PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter();
writer.startUpdate(comp.getClientId(ctx));
// do the default behavior...
comp.encodeAll(ctx);
writer.endUpdate();
} else {
throw new IllegalStateException("I18N: Unexpected " +
"PhaseId passed to " +
" PhaseAwareContextCallback: " +
curPhase.toString());
}
}
catch (IOException ex) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe(ex.toString());
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ex.toString(),
ex);
}
throw new FacesException(ex);
}
// Once we visit a component, there is no need to visit
// its children, since processDecodes/Validators/Updates and
// encodeAll() already traverse the subtree. We return
// VisitResult.REJECT to supress the subtree visit.
return VisitResult.REJECT;
}
}
/**
* Delays the actual construction of the PartialResponseWriter <em>until</em>
* content is going to actually be written.
*/
private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter {
private ResponseWriter writer;
private PartialViewContextImpl ctx;
// -------------------------------------------------------- Constructors
public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) {
super(null);
this.ctx = ctx;
ExternalContext extCtx = ctx.ctx.getExternalContext();
extCtx.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE);
extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding());
extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize());
}
// ---------------------------------- Methods from PartialResponseWriter
@Override
public void write(String text) throws IOException {
HtmlUtils.writeUnescapedTextForXML(getWrapped(), text);
}
@Override
public ResponseWriter getWrapped() {
if (writer == null) {
writer = ctx.createPartialResponseWriter();
}
return writer;
}
} // END DelayedInitPartialResponseWriter
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_1163_0 |
crossvul-java_data_good_5841_1 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.wicket.autocompletion;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptReferenceHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.handler.TextRequestHandler;
import org.apache.wicket.util.string.Strings;
import org.projectforge.web.core.JsonBuilder;
import org.projectforge.web.wicket.WicketRenderHeadUtils;
public abstract class PFAutoCompleteBehavior<T> extends AbstractDefaultAjaxBehavior
{
private static final long serialVersionUID = -6532710378025987377L;
protected PFAutoCompleteSettings settings;
protected IAutoCompleteRenderer<String> renderer;
public PFAutoCompleteBehavior(final IAutoCompleteRenderer<String> renderer, final PFAutoCompleteSettings settings)
{
this.renderer = renderer;
this.settings = settings;
}
/**
* @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#renderHead(org.apache.wicket.Component,
* org.apache.wicket.markup.html.IHeaderResponse)
*/
@Override
public void renderHead(final Component component, final IHeaderResponse response)
{
super.renderHead(component, response);
WicketRenderHeadUtils.renderMainJavaScriptIncludes(response);
response.render(JavaScriptReferenceHeaderItem.forUrl("scripts/jquery.wicket-autocomplete.js"));
renderAutocompleteHead(response);
}
/**
* Render autocomplete init javascript and other head contributions
*
* @param response
*/
private void renderAutocompleteHead(final IHeaderResponse response)
{
final String id = getComponent().getMarkupId();
String indicatorId = findIndicatorId();
if (Strings.isEmpty(indicatorId)) {
indicatorId = "null";
} else {
indicatorId = "'" + indicatorId + "'";
}
final StringBuffer buf = new StringBuffer();
buf.append("var favorite" + id + " = ");
final List<T> favorites = getFavorites();
final MyJsonBuilder builder = new MyJsonBuilder();
if (favorites != null) {
buf.append(builder.append(favorites).getAsString());
} else {
buf.append(builder.append(getRecentUserInputs()).getAsString());
}
buf.append(";").append("var z = $(\"#").append(id).append("\");\n").append("z.autocomplete(\"").append(getCallbackUrl()).append("\",{");
boolean first = true;
for (final String setting : getSettingsJS()) {
if (first == true)
first = false;
else buf.append(", ");
buf.append(setting);
}
if (first == true)
first = false;
else buf.append(", ");
buf.append("favoriteEntries:favorite" + id);
buf.append("});");
if (settings.isHasFocus() == true) {
buf.append("\nz.focus();");
}
final String initJS = buf.toString();
// String initJS = String.format("new Wicket.AutoComplete('%s','%s',%s,%s);", id, getCallbackUrl(), constructSettingsJS(), indicatorId);
response.render(OnDomReadyHeaderItem.forScript(initJS));
}
protected final List<String> getSettingsJS()
{
final List<String> result = new ArrayList<String>();
addSetting(result, "matchContains", settings.isMatchContains());
addSetting(result, "minChars", settings.getMinChars());
addSetting(result, "delay", settings.getDelay());
addSetting(result, "matchCase", settings.isMatchCase());
addSetting(result, "matchSubset", settings.isMatchSubset());
addSetting(result, "cacheLength", settings.getCacheLength());
addSetting(result, "mustMatch", settings.isMustMatch());
addSetting(result, "selectFirst", settings.isSelectFirst());
addSetting(result, "selectOnly", settings.isSelectOnly());
addSetting(result, "maxItemsToShow", settings.getMaxItemsToShow());
addSetting(result, "autoFill", settings.isAutoFill());
addSetting(result, "autoSubmit", settings.isAutoSubmit());
addSetting(result, "scroll", settings.isScroll());
addSetting(result, "scrollHeight", settings.getScrollHeight());
addSetting(result, "width", settings.getWidth());
addSetting(result, "deletableItem", settings.isDeletableItem());
if (settings.isLabelValue() == true) {
addSetting(result, "labelValue", settings.isLabelValue());
}
return result;
}
private final void addSetting(final List<String> result, final String name, final Boolean value)
{
if (value == null) {
return;
}
result.add(name + ":" + ((value == true) ? "1" : "0"));
}
private final void addSetting(final List<String> result, final String name, final Integer value)
{
if (value == null) {
return;
}
result.add(name + ":" + value);
}
/**
* @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#onBind()
*/
@Override
protected void onBind()
{
// add empty AbstractDefaultAjaxBehavior to the component, to force
// rendering wicket-ajax.js reference if no other ajax behavior is on
// page
getComponent().add(new AbstractDefaultAjaxBehavior() {
private static final long serialVersionUID = 1L;
@Override
protected void respond(final AjaxRequestTarget target)
{
}
});
}
/**
* @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#respond(org.apache.wicket.ajax.AjaxRequestTarget)
*/
@Override
protected void respond(final AjaxRequestTarget target)
{
final RequestCycle requestCycle = RequestCycle.get();
final org.apache.wicket.util.string.StringValue val = requestCycle.getRequest().getQueryParameters().getParameterValue("q");
onRequest(val != null ? val.toString() : null, requestCycle);
}
protected final void onRequest(final String val, final RequestCycle requestCycle)
{
// final PageParameters pageParameters = new PageParameters(requestCycle.getRequest().getParameterMap());
final List<T> choices = getChoices(val);
final MyJsonBuilder builder = new MyJsonBuilder();
final String json = builder.append(choices).getAsString();
requestCycle.scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "utf-8", json));
/*
* IRequestTarget target = new IRequestTarget() {
*
* public void respond(RequestCycle requestCycle) {
*
* WebResponse r = (WebResponse) requestCycle.getResponse(); // Determine encoding final String encoding =
* Application.get().getRequestCycleSettings().getResponseRequestEncoding(); r.setCharacterEncoding(encoding);
* r.setContentType("application/json"); // Make sure it is not cached by a r.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
* r.setHeader("Cache-Control", "no-cache, must-revalidate"); r.setHeader("Pragma", "no-cache");
*
* final List<T> choices = getChoices(val); renderer.renderHeader(r); renderer.render(JsonBuilder.buildRows(false, choices), r, val);
* renderer.renderFooter(r); }
*
* public void detach(RequestCycle requestCycle) { } }; requestCycle.setRequestTarget(target);
*/
}
/**
* Callback method that should return an iterator over all possible choice objects. These objects will be passed to the renderer to
* generate output. Usually it is enough to return an iterator over strings.
*
* @param input current input
* @return iterator over all possible choice objects
*/
protected abstract List<T> getChoices(String input);
/**
* Callback method that should return a list of all possible default choice objects to show, if the user double clicks the empty input
* field. These objects will be passed to the renderer to generate output. Usually it is enough to return an iterator over strings.
*/
protected abstract List<T> getFavorites();
/**
* Callback method that should return a list of all recent user inputs in the text input field. They will be shown, if the user double
* clicks the empty input field. These objects will be passed to the renderer to generate output. Usually it is enough to return an
* iterator over strings. <br/>
* Please note: Please, use only getFavorites() OR getRecentUserInputs()!
*/
protected abstract List<String> getRecentUserInputs();
/**
* Used for formatting the values.
*/
protected abstract String formatValue(T value);
/**
* Used for formatting the labels if labelValue is set to true.
* @return null at default (if not overload).
*/
protected String formatLabel(final T value)
{
return null;
}
private class MyJsonBuilder extends JsonBuilder
{
private MyJsonBuilder()
{
setEscapeHtml(true);
}
@SuppressWarnings("unchecked")
@Override
protected String formatValue(final Object obj)
{
if (obj instanceof String) {
return obj.toString();
} else {
return PFAutoCompleteBehavior.this.formatValue((T) obj);
}
}
@SuppressWarnings("unchecked")
@Override
protected Object transform(final Object obj)
{
if (settings.isLabelValue() == true) {
final Object[] oa = new Object[2];
if (obj instanceof String) {
oa[0] = obj;
oa[1] = obj;
} else {
oa[0] = PFAutoCompleteBehavior.this.formatLabel((T) obj);
oa[1] = PFAutoCompleteBehavior.this.formatValue((T) obj);
}
return oa;
} else {
return obj;
}
}
};
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_5841_1 |
crossvul-java_data_bad_4990_1 | /**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.nav;
import com.redhat.rhn.frontend.html.HtmlTag;
import java.util.Map;
import java.util.StringTokenizer;
/**
* DialognavRenderer - renders a navigation bar
*
* Renders the navigation inside the content, which is implemented
* as rows of Twitter Bootstrap tabs (nav-tabs)
*
* The navigation is enclosed in a div styled with class
* 'spacewalk-content-nav' and the individual rows can be styled by
* ul:nth-child selectors.
*
* @version $Rev$
*/
public class DialognavRenderer extends Renderable {
private final StringBuffer titleBuf;
/**
* Public constructor
*/
public DialognavRenderer() {
// empty
titleBuf = new StringBuffer();
}
/** {@inheritDoc} */
@Override
public void preNav(StringBuffer sb) {
HtmlTag div = new HtmlTag("div");
div.setAttribute("class", "spacewalk-content-nav");
sb.append(div.renderOpenTag());
}
/** {@inheritDoc} */
@Override
public void preNavLevel(StringBuffer sb, int depth) {
if (!canRender(null, depth)) {
return;
}
HtmlTag ul = new HtmlTag("ul");
if (depth == 0) {
ul.setAttribute("class", "nav nav-tabs");
}
else {
ul.setAttribute("class", "nav nav-tabs nav-tabs-pf");
}
sb.append(ul.renderOpenTag());
}
/** {@inheritDoc} */
@Override
public void preNavNode(StringBuffer sb, int depth) {
}
/** {@inheritDoc} */
@Override
public void navNodeActive(StringBuffer sb,
NavNode node,
NavTreeIndex treeIndex,
Map parameters,
int depth) {
if (!canRender(node, depth)) {
return;
}
titleBuf.append(" - " + node.getName());
renderNode(sb, node, treeIndex, parameters,
"active");
}
/** {@inheritDoc} */
@Override
public void navNodeInactive(StringBuffer sb,
NavNode node,
NavTreeIndex treeIndex,
Map parameters,
int depth) {
if (!canRender(node, depth)) {
return;
}
renderNode(sb, node, treeIndex, parameters, "");
}
private void renderNode(StringBuffer sb, NavNode node,
NavTreeIndex treeIndex, Map parameters,
String cssClass) {
HtmlTag li = new HtmlTag("li");
if (!cssClass.equals("")) {
li.setAttribute("class", cssClass);
}
String href = node.getPrimaryURL();
String allowedFormVars = treeIndex.getTree().getFormvar();
if (allowedFormVars != null) {
StringBuilder formVars;
if (href.indexOf('?') == -1) {
formVars = new StringBuilder("?");
}
else {
formVars = new StringBuilder("&");
}
StringTokenizer st = new StringTokenizer(allowedFormVars);
while (st.hasMoreTokens()) {
if (formVars.length() > 1) {
formVars.append("&");
}
String currentVar = st.nextToken();
String[] values = (String[])parameters.get(currentVar);
// if currentVar is null, values will be null too, so we can
// just check values.
if (values != null) {
formVars.append(currentVar + "=" + values[0]);
}
}
href += formVars.toString();
}
li.addBody(aHref(href, node.getName(), node.getTarget()));
sb.append(li.render());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public void postNavNode(StringBuffer sb, int depth) {
}
/** {@inheritDoc} */
@Override
public void postNavLevel(StringBuffer sb, int depth) {
if (!canRender(null, depth)) {
return;
}
HtmlTag ul = new HtmlTag("ul");
sb.append(ul.renderCloseTag());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public void postNav(StringBuffer sb) {
HtmlTag div = new HtmlTag("div");
sb.append(div.renderCloseTag());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public boolean nodeRenderInline(int depth) {
return false;
}
private static String aHref(String url, String text, String target) {
HtmlTag a = new HtmlTag("a");
if (target != null && !target.equals("")) {
a.setAttribute("target", target);
}
a.setAttribute("href", url);
a.addBody(text);
return a.render();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_4990_1 |
crossvul-java_data_good_4990_1 | /**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.nav;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringEscapeUtils;
import com.redhat.rhn.frontend.html.HtmlTag;
/**
* DialognavRenderer - renders a navigation bar
*
* Renders the navigation inside the content, which is implemented
* as rows of Twitter Bootstrap tabs (nav-tabs)
*
* The navigation is enclosed in a div styled with class
* 'spacewalk-content-nav' and the individual rows can be styled by
* ul:nth-child selectors.
*
* @version $Rev$
*/
public class DialognavRenderer extends Renderable {
private final StringBuffer titleBuf;
/**
* Public constructor
*/
public DialognavRenderer() {
// empty
titleBuf = new StringBuffer();
}
/** {@inheritDoc} */
@Override
public void preNav(StringBuffer sb) {
HtmlTag div = new HtmlTag("div");
div.setAttribute("class", "spacewalk-content-nav");
sb.append(div.renderOpenTag());
}
/** {@inheritDoc} */
@Override
public void preNavLevel(StringBuffer sb, int depth) {
if (!canRender(null, depth)) {
return;
}
HtmlTag ul = new HtmlTag("ul");
if (depth == 0) {
ul.setAttribute("class", "nav nav-tabs");
}
else {
ul.setAttribute("class", "nav nav-tabs nav-tabs-pf");
}
sb.append(ul.renderOpenTag());
}
/** {@inheritDoc} */
@Override
public void preNavNode(StringBuffer sb, int depth) {
}
/** {@inheritDoc} */
@Override
public void navNodeActive(StringBuffer sb,
NavNode node,
NavTreeIndex treeIndex,
Map parameters,
int depth) {
if (!canRender(node, depth)) {
return;
}
titleBuf.append(" - " + node.getName());
renderNode(sb, node, treeIndex, parameters,
"active");
}
/** {@inheritDoc} */
@Override
public void navNodeInactive(StringBuffer sb,
NavNode node,
NavTreeIndex treeIndex,
Map parameters,
int depth) {
if (!canRender(node, depth)) {
return;
}
renderNode(sb, node, treeIndex, parameters, "");
}
private void renderNode(StringBuffer sb, NavNode node,
NavTreeIndex treeIndex, Map parameters,
String cssClass) {
HtmlTag li = new HtmlTag("li");
if (!cssClass.equals("")) {
li.setAttribute("class", cssClass);
}
String href = node.getPrimaryURL();
String allowedFormVars = treeIndex.getTree().getFormvar();
if (allowedFormVars != null) {
StringBuilder formVars;
if (href.indexOf('?') == -1) {
formVars = new StringBuilder("?");
}
else {
formVars = new StringBuilder("&");
}
StringTokenizer st = new StringTokenizer(allowedFormVars);
while (st.hasMoreTokens()) {
if (formVars.length() > 1) {
formVars.append("&");
}
String currentVar = st.nextToken();
String[] values = (String[])parameters.get(currentVar);
// if currentVar is null, values will be null too, so we can
// just check values.
if (values != null) {
formVars.append(currentVar + "=" +
StringEscapeUtils.escapeHtml(values[0]));
}
}
href += formVars.toString();
}
li.addBody(aHref(href, node.getName(), node.getTarget()));
sb.append(li.render());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public void postNavNode(StringBuffer sb, int depth) {
}
/** {@inheritDoc} */
@Override
public void postNavLevel(StringBuffer sb, int depth) {
if (!canRender(null, depth)) {
return;
}
HtmlTag ul = new HtmlTag("ul");
sb.append(ul.renderCloseTag());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public void postNav(StringBuffer sb) {
HtmlTag div = new HtmlTag("div");
sb.append(div.renderCloseTag());
sb.append("\n");
}
/** {@inheritDoc} */
@Override
public boolean nodeRenderInline(int depth) {
return false;
}
private static String aHref(String url, String text, String target) {
HtmlTag a = new HtmlTag("a");
if (target != null && !target.equals("")) {
a.setAttribute("target", target);
}
a.setAttribute("href", url);
a.addBody(text);
return a.render();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_4990_1 |
crossvul-java_data_bad_4174_1 | package org.mapfish.print.servlet;
import net.sf.jasperreports.engine.fonts.FontFamily;
import net.sf.jasperreports.extensions.ExtensionsEnvironment;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jfree.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import org.mapfish.print.Constants;
import org.mapfish.print.ExceptionUtils;
import org.mapfish.print.MapPrinter;
import org.mapfish.print.MapPrinterFactory;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.Template;
import org.mapfish.print.processor.Processor;
import org.mapfish.print.processor.http.matcher.UriMatchers;
import org.mapfish.print.servlet.job.JobManager;
import org.mapfish.print.servlet.job.NoSuchReferenceException;
import org.mapfish.print.servlet.job.PrintJobStatus;
import org.mapfish.print.servlet.job.impl.PrintJobEntryImpl;
import org.mapfish.print.servlet.job.impl.ThreadPoolJobManager;
import org.mapfish.print.servlet.job.loader.ReportLoader;
import org.mapfish.print.url.data.Handler;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.mapfish.print.servlet.ServletMapPrinterFactory.DEFAULT_CONFIGURATION_FILE_KEY;
/**
* The default servlet.
*/
@Controller
public class MapPrinterServlet extends BaseMapServlet {
/**
* The url path for capabilities requests.
*/
public static final String CAPABILITIES_URL = "/capabilities.json";
/**
* The url path to list all registered configurations.
*/
public static final String LIST_APPS_URL = "/apps.json";
/**
* The url path to get a sample print request.
*/
public static final String EXAMPLE_REQUEST_URL = "/exampleRequest.json";
/**
* The url path to create and get a report.
*/
public static final String CREATE_AND_GET_URL = "/buildreport";
/**
* The url path to get the status for a print task.
*/
public static final String STATUS_URL = "/status";
/**
* The url path to cancel a print task.
*/
public static final String CANCEL_URL = "/cancel";
/**
* The url path to create a print task and to get a finished print.
*/
public static final String REPORT_URL = "/report";
/**
* The url path to get the list of fonts available to geotools.
*/
public static final String FONTS_URL = "/fonts";
/**
* The key containing an error message for failed jobs.
*/
public static final String JSON_ERROR = "error";
/**
* The application ID which indicates the configuration file to load.
*/
public static final String JSON_APP = "app";
/* Registry keys */
/**
* If the job is done (value is true) or not (value is false).
*
* Part of the {@link #getStatus(String, String, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)} response.
*/
public static final String JSON_DONE = "done";
/**
* The status of the job. One of the following values:
* <ul>
* <li>waiting</li>
* <li>running</li>
* <li>finished</li>
* <li>cancelled</li>
* <li>error</li>
* </ul>
* Part of the {@link #getStatus(String, String, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)} response
*/
public static final String JSON_STATUS = "status";
/**
* The elapsed time in ms from the point the job started. If the job is finished, this is the duration it
* took to process the job.
*
* Part of the {@link #getStatus(String, String, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)} response.
*/
public static final String JSON_ELAPSED_TIME = "elapsedTime";
/**
* A rough estimate for the time in ms the job still has to wait in the queue until it starts processing.
*
* Part of the {@link #getStatus(String, String, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)} response.
*/
public static final String JSON_WAITING_TIME = "waitingTime";
/**
* The key containing the print job reference ID in the create report response.
*/
public static final String JSON_PRINT_JOB_REF = "ref";
/**
* The json key in the create report response containing a link to get the status of the print job.
*/
public static final String JSON_STATUS_LINK = "statusURL";
/**
* The json key in the create report and status responses containing a link to download the report.
*/
public static final String JSON_DOWNLOAD_LINK = "downloadURL";
/**
* The JSON key in the request spec that contains the outputFormat. This value will be put into the spec
* by the servlet. there is not need for the post to do this.
*/
public static final String JSON_OUTPUT_FORMAT = "outputFormat";
/**
* The json tag referring to the attributes.
*/
public static final String JSON_ATTRIBUTES = "attributes";
/**
* The json property to add the request headers from the print request.
* <p>
* The request headers from the print request are needed by certain processors, the headers are added to
* the request JSON data for those processors.
*/
public static final String JSON_REQUEST_HEADERS = "requestHeaders";
private static final Logger LOGGER = LoggerFactory.getLogger(MapPrinterServlet.class);
private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{(\\S+)}");
private static final int JSON_INDENT_FACTOR = 4;
private static final List<String> REQUEST_ID_HEADERS = Arrays.asList(
"X-Request-ID",
"X-Correlation-ID",
"Request-ID",
"X-Varnish",
"X-Amzn-Trace-Id"
);
static {
Handler.configureProtocolHandler();
}
private final JobManager jobManager;
private final List<ReportLoader> reportLoaders;
private final MapPrinterFactory printerFactory;
private final ApplicationContext context;
private final ServletInfo servletInfo;
private final MapPrinterFactory mapPrinterFactory;
private long maxCreateAndGetWaitTimeInSeconds = ThreadPoolJobManager.DEFAULT_TIMEOUT_IN_SECONDS;
@Autowired
public MapPrinterServlet(
final JobManager jobManager, final List<ReportLoader> reportLoaders,
final MapPrinterFactory printerFactory, final ApplicationContext context,
final ServletInfo servletInfo, final MapPrinterFactory mapPrinterFactory) {
this.jobManager = jobManager;
this.reportLoaders = reportLoaders;
this.printerFactory = printerFactory;
this.context = context;
this.servletInfo = servletInfo;
this.mapPrinterFactory = mapPrinterFactory;
}
/**
* Parse the print request json data.
*
* @param requestDataRaw the request json in string form
* @param httpServletResponse the response object to use for returning errors if needed
*/
private static PJsonObject parseJson(
final String requestDataRaw, final HttpServletResponse httpServletResponse) {
try {
if (requestDataRaw == null) {
error(httpServletResponse,
"Missing post data. The post payload must either be a form post with a spec " +
"parameter or " +
"must be a raw json post with the request.", HttpStatus.INTERNAL_SERVER_ERROR);
return null;
}
String requestData = requestDataRaw;
if (!requestData.startsWith("spec=") && !requestData.startsWith("{")) {
try {
requestData = URLDecoder.decode(requestData, Constants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
if (requestData.startsWith("spec=")) {
requestData = requestData.substring("spec=".length());
}
try {
return MapPrinter.parseSpec(requestData);
} catch (RuntimeException e) {
try {
return MapPrinter.parseSpec(URLDecoder.decode(requestData, Constants.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException uee) {
throw ExceptionUtils.getRuntimeException(e);
}
}
} catch (RuntimeException e) {
LOGGER.warn("Error parsing request data: {}", requestDataRaw);
throw e;
}
}
/**
* If the request contains a header that specifies a request ID, add it to the ref. The ref shows up in
* every logs, that way, we can trace the request ID across applications.
*/
private static String maybeAddRequestId(final String ref, final HttpServletRequest request) {
final Optional<String> headerName =
REQUEST_ID_HEADERS.stream().filter(h -> request.getHeader(h) != null).findFirst();
return headerName.map(s -> ref + "@" + request.getHeader(s).replaceAll("[^a-zA-Z0-9._:-]", "_")
).orElse(ref);
}
/**
* Get a status report on a job. Returns the following json:
*
* <pre><code>
* {"time":0,"count":0,"done":false}
* </code></pre>
*
* @param appId the app ID
* @param referenceId the job reference
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param statusRequest the request object
* @param statusResponse the response object
*/
@RequestMapping(value = "/{appId}" + STATUS_URL + "/{referenceId:\\S+}.json", method = RequestMethod.GET)
public final void getStatusSpecificAppId(
@SuppressWarnings("unused") @PathVariable final String appId,
@PathVariable final String referenceId,
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest statusRequest,
final HttpServletResponse statusResponse) {
getStatus(referenceId, jsonpCallback, statusRequest, statusResponse);
}
/**
* Get a status report on a job. Returns the following json:
*
* <pre><code>
* {"time":0,"count":0,"done":false}
* </code></pre>
*
* @param referenceId the job reference
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param statusRequest the request object
* @param statusResponse the response object
*/
@RequestMapping(value = STATUS_URL + "/{referenceId:\\S+}.json", method = RequestMethod.GET)
public final void getStatus(
@PathVariable final String referenceId,
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest statusRequest,
final HttpServletResponse statusResponse) {
MDC.put(Processor.MDC_JOB_ID_KEY, referenceId);
setNoCache(statusResponse);
try {
PrintJobStatus status = this.jobManager.getStatus(referenceId);
setContentType(statusResponse, jsonpCallback);
try (PrintWriter writer = statusResponse.getWriter()) {
appendJsonpCallback(jsonpCallback, writer);
JSONWriter json = new JSONWriter(writer);
json.object();
{
json.key(JSON_DONE).value(status.isDone());
json.key(JSON_STATUS).value(status.getStatus().toString().toLowerCase());
json.key(JSON_ELAPSED_TIME).value(status.getElapsedTime());
json.key(JSON_WAITING_TIME).value(status.getWaitingTime());
if (!StringUtils.isEmpty(status.getError())) {
json.key(JSON_ERROR).value(status.getError());
}
addDownloadLinkToJson(statusRequest, referenceId, json);
}
json.endObject();
appendJsonpCallbackEnd(jsonpCallback, writer);
}
} catch (JSONException | IOException e) {
throw ExceptionUtils.getRuntimeException(e);
} catch (NoSuchReferenceException e) {
error(statusResponse, e.getMessage(), HttpStatus.NOT_FOUND);
}
}
/**
* Cancel a job.
* <p>
* Even if a job was already finished, subsequent status requests will return that the job was canceled.
*
* @param appId the app ID
* @param referenceId the job reference
* @param statusResponse the response object
*/
@RequestMapping(value = "/{appId}" + CANCEL_URL + "/{referenceId:\\S+}", method = RequestMethod.DELETE)
public final void cancelSpecificAppId(
@SuppressWarnings("unused") @PathVariable final String appId,
@PathVariable final String referenceId,
final HttpServletResponse statusResponse) {
cancel(referenceId, statusResponse);
}
/**
* Cancel a job.
* <p>
* Even if a job was already finished, subsequent status requests will return that the job was canceled.
*
* @param referenceId the job reference
* @param statusResponse the response object
*/
@RequestMapping(value = CANCEL_URL + "/{referenceId:\\S+}", method = RequestMethod.DELETE)
public final void cancel(
@PathVariable final String referenceId,
final HttpServletResponse statusResponse) {
MDC.put(Processor.MDC_JOB_ID_KEY, referenceId);
setNoCache(statusResponse);
try {
this.jobManager.cancel(referenceId);
} catch (NoSuchReferenceException e) {
error(statusResponse, e.getMessage(), HttpStatus.NOT_FOUND);
}
}
/**
* Add the print job to the job queue.
*
* @param appId the id of the app to get the request for.
* @param format the format of the returned report
* @param requestData a json formatted string with the request data required to perform the report
* generation.
* @param createReportRequest the request object
* @param createReportResponse the response object
*/
@RequestMapping(value = "/{appId}" + REPORT_URL + ".{format:\\w+}", method = RequestMethod.POST)
public final void createReport(
@PathVariable final String appId,
@PathVariable final String format,
@RequestBody final String requestData,
final HttpServletRequest createReportRequest,
final HttpServletResponse createReportResponse) throws NoSuchAppException {
setNoCache(createReportResponse);
String ref = createAndSubmitPrintJob(appId, format, requestData, createReportRequest,
createReportResponse);
if (ref == null) {
error(createReportResponse, "Failed to create a print job", HttpStatus.INTERNAL_SERVER_ERROR);
return;
}
createReportResponse.setContentType("application/json; charset=utf-8");
try (PrintWriter writer = createReportResponse.getWriter()) {
JSONWriter json = new JSONWriter(writer);
json.object();
{
json.key(JSON_PRINT_JOB_REF).value(ref);
String statusURL = getBaseUrl(createReportRequest) + STATUS_URL + "/" + ref + ".json";
json.key(JSON_STATUS_LINK).value(statusURL);
addDownloadLinkToJson(createReportRequest, ref, json);
}
json.endObject();
} catch (JSONException | IOException e) {
LOGGER.warn("Error generating the JSON response", e);
}
}
/**
* To get the PDF created previously.
*
* @param appId the app ID
* @param referenceId the path to the file.
* @param inline whether or not to inline the
* @param getReportResponse the response object
*/
@RequestMapping(value = "/{appId}" + REPORT_URL + "/{referenceId:\\S+}", method = RequestMethod.GET)
public final void getReportSpecificAppId(
@SuppressWarnings("unused") @PathVariable final String appId,
@PathVariable final String referenceId,
@RequestParam(value = "inline", defaultValue = "false") final boolean inline,
final HttpServletResponse getReportResponse)
throws IOException, ServletException {
getReport(referenceId, inline, getReportResponse);
}
/**
* To get the PDF created previously.
*
* @param referenceId the path to the file.
* @param inline whether or not to inline the
* @param getReportResponse the response object
*/
@RequestMapping(value = REPORT_URL + "/{referenceId:\\S+}", method = RequestMethod.GET)
public final void getReport(
@PathVariable final String referenceId,
@RequestParam(value = "inline", defaultValue = "false") final boolean inline,
final HttpServletResponse getReportResponse)
throws IOException, ServletException {
MDC.put(Processor.MDC_JOB_ID_KEY, referenceId);
setNoCache(getReportResponse);
loadReport(referenceId, getReportResponse, new HandleReportLoadResult<Void>() {
@Override
public Void unknownReference(
final HttpServletResponse httpServletResponse, final String referenceId) {
error(httpServletResponse, "Error getting print with ref=" + referenceId +
": unknown reference",
HttpStatus.NOT_FOUND);
return null;
}
@Override
public Void unsupportedLoader(
final HttpServletResponse httpServletResponse, final String referenceId) {
error(httpServletResponse, "Error getting print with ref=" + referenceId +
" can not be loaded",
HttpStatus.NOT_FOUND);
return null;
}
@Override
public Void successfulPrint(
final PrintJobStatus successfulPrintResult, final HttpServletResponse httpServletResponse,
final URI reportURI, final ReportLoader loader) throws IOException {
sendReportFile(successfulPrintResult, httpServletResponse, loader, reportURI, inline);
return null;
}
@Override
public Void failedPrint(
final PrintJobStatus failedPrintJob, final HttpServletResponse httpServletResponse) {
error(httpServletResponse, failedPrintJob.getError(), HttpStatus.INTERNAL_SERVER_ERROR);
return null;
}
@Override
public Void printJobPending(
final HttpServletResponse httpServletResponse, final String referenceId) {
error(httpServletResponse, "Report has not yet completed processing", HttpStatus.ACCEPTED);
return null;
}
});
}
/**
* Add the print job to the job queue.
*
* @param format the format of the returned report
* @param requestData a json formatted string with the request data required to perform the report
* generation.
* @param createReportRequest the request object
* @param createReportResponse the response object
*/
@RequestMapping(value = REPORT_URL + ".{format:\\w+}", method = RequestMethod.POST)
public final void createReport(
@PathVariable final String format,
@RequestBody final String requestData,
final HttpServletRequest createReportRequest,
final HttpServletResponse createReportResponse) throws NoSuchAppException {
setNoCache(createReportResponse);
PJsonObject spec = parseJson(requestData, createReportResponse);
if (spec == null) {
return;
}
final String appId = spec.optString(JSON_APP, DEFAULT_CONFIGURATION_FILE_KEY);
createReport(appId, format, requestData, createReportRequest, createReportResponse);
}
/**
* add the print job to the job queue.
*
* @param appId the id of the app to get the request for.
* @param format the format of the returned report
* @param requestData a json formatted string with the request data required to perform the report
* generation.
* @param inline whether or not to inline the content
* @param createReportRequest the request object
* @param createReportResponse the response object
*/
@RequestMapping(value = "/{appId}" + CREATE_AND_GET_URL + ".{format:\\w+}", method = RequestMethod.POST)
public final void createReportAndGet(
@PathVariable final String appId,
@PathVariable final String format,
@RequestBody final String requestData,
@RequestParam(value = "inline", defaultValue = "false") final boolean inline,
final HttpServletRequest createReportRequest,
final HttpServletResponse createReportResponse)
throws IOException, ServletException, InterruptedException, NoSuchAppException {
setNoCache(createReportResponse);
String ref = createAndSubmitPrintJob(appId, format, requestData, createReportRequest,
createReportResponse);
if (ref == null) {
error(createReportResponse, "Failed to create a print job", HttpStatus.INTERNAL_SERVER_ERROR);
return;
}
final HandleReportLoadResult<Boolean> handler = new HandleReportLoadResult<Boolean>() {
@Override
public Boolean unknownReference(
final HttpServletResponse httpServletResponse, final String referenceId) {
error(httpServletResponse, "Print with ref=" + referenceId + " unknown",
HttpStatus.NOT_FOUND);
return true;
}
@Override
public Boolean unsupportedLoader(
final HttpServletResponse httpServletResponse, final String referenceId) {
error(httpServletResponse, "Print with ref=" + referenceId + " can not be loaded",
HttpStatus.NOT_FOUND);
return true;
}
@Override
public Boolean successfulPrint(
final PrintJobStatus successfulPrintResult,
final HttpServletResponse httpServletResponse,
final URI reportURI, final ReportLoader loader) throws IOException {
sendReportFile(successfulPrintResult, httpServletResponse, loader, reportURI, inline);
return true;
}
@Override
public Boolean failedPrint(
final PrintJobStatus failedPrintJob, final HttpServletResponse httpServletResponse) {
error(httpServletResponse, failedPrintJob.getError(), HttpStatus.INTERNAL_SERVER_ERROR);
return true;
}
@Override
public Boolean printJobPending(
final HttpServletResponse httpServletResponse, final String referenceId) {
return false;
}
};
boolean isDone = false;
long startWaitTime = System.currentTimeMillis();
final long maxWaitTimeInMillis = TimeUnit.SECONDS.toMillis(this.maxCreateAndGetWaitTimeInSeconds);
while (!isDone && System.currentTimeMillis() - startWaitTime < maxWaitTimeInMillis) {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
isDone = loadReport(ref, createReportResponse, handler);
}
}
/**
* add the print job to the job queue.
*
* @param format the format of the returned report
* @param requestData a json formatted string with the request data required to perform the report
* generation.
* @param inline whether or not to inline the content
* @param createReportRequest the request object
* @param createReportResponse the response object
*/
@RequestMapping(value = CREATE_AND_GET_URL + ".{format:\\w+}", method = RequestMethod.POST)
public final void createReportAndGetNoAppId(
@PathVariable final String format,
@RequestBody final String requestData,
@RequestParam(value = "inline", defaultValue = "false") final boolean inline,
final HttpServletRequest createReportRequest,
final HttpServletResponse createReportResponse)
throws IOException, ServletException, InterruptedException, NoSuchAppException {
setNoCache(createReportResponse);
PJsonObject spec = parseJson(requestData, createReportResponse);
if (spec == null) {
return;
}
String appId = spec.optString(JSON_APP, DEFAULT_CONFIGURATION_FILE_KEY);
createReportAndGet(appId, format, requestData, inline, createReportRequest, createReportResponse);
}
/**
* To get (in JSON) the information about the available formats and CO.
*
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param listAppsResponse the response object
*/
@RequestMapping(value = LIST_APPS_URL, method = RequestMethod.GET)
public final void listAppIds(
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletResponse listAppsResponse) throws ServletException,
IOException {
MDC.remove(Processor.MDC_JOB_ID_KEY);
setCache(listAppsResponse);
Set<String> appIds = this.printerFactory.getAppIds();
setContentType(listAppsResponse, jsonpCallback);
try (PrintWriter writer = listAppsResponse.getWriter()) {
appendJsonpCallback(jsonpCallback, writer);
JSONWriter json = new JSONWriter(writer);
try {
json.array();
for (String appId: appIds) {
json.value(appId);
}
json.endArray();
} catch (JSONException e) {
throw new ServletException(e);
}
appendJsonpCallbackEnd(jsonpCallback, writer);
}
}
/**
* To get (in JSON) the information about the available formats and CO.
*
* @param pretty if true then pretty print the capabilities
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param request the request
* @param capabilitiesResponse the response object
*/
@RequestMapping(value = CAPABILITIES_URL, method = RequestMethod.GET)
public final void getCapabilities(
@RequestParam(value = "pretty", defaultValue = "false") final boolean pretty,
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest request,
final HttpServletResponse capabilitiesResponse) throws ServletException,
IOException {
getCapabilities(DEFAULT_CONFIGURATION_FILE_KEY, pretty, jsonpCallback, request, capabilitiesResponse);
}
/**
* To get (in JSON) the information about the available formats and CO.
*
* @param appId the name of the "app" or in other words, a mapping to the configuration file for
* this request.
* @param pretty if true then pretty print the capabilities
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param request the request
* @param capabilitiesResponse the response object
*/
@RequestMapping(value = "/{appId}" + CAPABILITIES_URL, method = RequestMethod.GET)
public final void getCapabilities(
@PathVariable final String appId,
@RequestParam(value = "pretty", defaultValue = "false") final boolean pretty,
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest request,
final HttpServletResponse capabilitiesResponse) throws ServletException,
IOException {
MDC.remove(Processor.MDC_JOB_ID_KEY);
setCache(capabilitiesResponse);
MapPrinter printer;
try {
printer = this.printerFactory.create(appId);
if (!checkReferer(request, printer)) {
error(capabilitiesResponse, "Invalid referer", HttpStatus.FORBIDDEN);
return;
}
} catch (NoSuchAppException e) {
error(capabilitiesResponse, e.getMessage(), HttpStatus.NOT_FOUND);
return;
}
setContentType(capabilitiesResponse, jsonpCallback);
final ByteArrayOutputStream prettyPrintBuffer = new ByteArrayOutputStream();
try (Writer writer = pretty ? new OutputStreamWriter(prettyPrintBuffer, Constants.DEFAULT_CHARSET) :
capabilitiesResponse.getWriter()) {
if (!pretty && !StringUtils.isEmpty(jsonpCallback)) {
writer.append(jsonpCallback).append("(");
}
JSONWriter json = new JSONWriter(writer);
try {
json.object();
{
json.key(JSON_APP).value(appId);
printer.printClientConfig(json);
}
{
json.key("formats");
Set<String> formats = printer.getOutputFormatsNames();
json.array();
for (String format: formats) {
json.value(format);
}
json.endArray();
}
json.endObject();
} catch (JSONException e) {
throw new ServletException(e);
}
if (!pretty && !StringUtils.isEmpty(jsonpCallback)) {
writer.append(");");
}
}
if (pretty) {
final JSONObject jsonObject =
new JSONObject(new String(prettyPrintBuffer.toByteArray(), Constants.DEFAULT_CHARSET));
if (!StringUtils.isEmpty(jsonpCallback)) {
capabilitiesResponse.getOutputStream().print(jsonpCallback + "(");
}
capabilitiesResponse.getOutputStream().print(jsonObject.toString(JSON_INDENT_FACTOR));
if (!StringUtils.isEmpty(jsonpCallback)) {
capabilitiesResponse.getOutputStream().print(");");
}
}
}
/**
* Get a sample request for the app. An empty response may be returned if there is not example request.
*
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param request the request object
* @param getExampleResponse the response object
*/
@RequestMapping(value = EXAMPLE_REQUEST_URL, method = RequestMethod.GET)
public final void getExampleRequest(
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest request,
final HttpServletResponse getExampleResponse) throws IOException {
getExampleRequest(DEFAULT_CONFIGURATION_FILE_KEY, jsonpCallback, request, getExampleResponse);
}
/**
* Get a sample request for the app. An empty response may be returned if there is not example request.
*
* @param appId the id of the app to get the request for.
* @param jsonpCallback if given the result is returned with a function call wrapped around it
* @param request the request object
* @param getExampleResponse the response object
*/
@RequestMapping(value = "{appId}" + EXAMPLE_REQUEST_URL, method = RequestMethod.GET)
public final void getExampleRequest(
@PathVariable final String appId,
@RequestParam(value = "jsonp", defaultValue = "") final String jsonpCallback,
final HttpServletRequest request,
final HttpServletResponse getExampleResponse) throws
IOException {
MDC.remove(Processor.MDC_JOB_ID_KEY);
setCache(getExampleResponse);
try {
final MapPrinter mapPrinter = this.printerFactory.create(appId);
if (!checkReferer(request, mapPrinter)) {
error(getExampleResponse, "Invalid referer", HttpStatus.FORBIDDEN);
return;
}
final String requestDataPrefix = "requestData";
final File[] children =
mapPrinter.getConfiguration().getDirectory().listFiles(
(dir, name) -> name.startsWith(requestDataPrefix) && name.endsWith(".json"));
if (children == null) {
error(getExampleResponse, "Cannot find the config directory", HttpStatus.NOT_FOUND);
return;
}
JSONObject allExamples = new JSONObject();
for (File child: children) {
if (child.isFile()) {
String requestData = new String(Files.readAllBytes(child.toPath()),
Constants.DEFAULT_CHARSET);
try {
final JSONObject jsonObject = new JSONObject(requestData);
jsonObject.remove(JSON_OUTPUT_FORMAT);
jsonObject.remove(JSON_APP);
requestData = jsonObject.toString(JSON_INDENT_FACTOR);
setContentType(getExampleResponse, jsonpCallback);
} catch (JSONException e) {
// ignore, return raw text
}
String name = child.getName();
name = name.substring(requestDataPrefix.length());
if (name.startsWith("-")) {
name = name.substring(1);
}
name = FilenameUtils.removeExtension(name);
name = name.trim();
if (name.isEmpty()) {
name = FilenameUtils.removeExtension(child.getName());
}
try {
allExamples.put(name, requestData);
} catch (JSONException e) {
Log.error("Error translating object to json", e);
error(getExampleResponse, "Error translating object to json: " + e.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
return;
}
}
}
final String result;
try {
result = allExamples.toString(JSON_INDENT_FACTOR);
} catch (JSONException e) {
Log.error("Error translating object to json", e);
error(getExampleResponse, "Error translating object to json: " + e.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
return;
}
try (PrintWriter writer = getExampleResponse.getWriter()) {
appendJsonpCallback(jsonpCallback, writer);
writer.append(result);
appendJsonpCallbackEnd(jsonpCallback, writer);
}
} catch (NoSuchAppException e) {
error(getExampleResponse, "No print app identified by: " + appId, HttpStatus.NOT_FOUND);
}
}
/**
* List the available fonts on the system.
*
* @return the list of available fonts in the system. The result is a JSON Array that just lists the font
* family names available.
*/
@RequestMapping(value = FONTS_URL)
@ResponseBody
public final String listAvailableFonts() {
MDC.remove(Processor.MDC_JOB_ID_KEY);
final JSONArray availableFonts = new JSONArray();
final List<FontFamily> families =
ExtensionsEnvironment.getExtensionsRegistry().getExtensions(FontFamily.class);
for (FontFamily family: families) {
availableFonts.put(family.getName());
}
return availableFonts.toString();
}
/**
* Maximum time to wait for a createAndGet request to complete before returning an error.
*
* @param maxCreateAndGetWaitTimeInSeconds the maximum time in seconds to wait for a report to be
* generated.
*/
public final void setMaxCreateAndGetWaitTimeInSeconds(final long maxCreateAndGetWaitTimeInSeconds) {
this.maxCreateAndGetWaitTimeInSeconds = maxCreateAndGetWaitTimeInSeconds;
}
/**
* Copy the PDF into the output stream.
*
* @param metadata the client request data
* @param httpServletResponse the response object
* @param reportLoader the object used for loading the report
* @param reportURI the uri of the report
* @param inline whether or not to inline the content
*/
private void sendReportFile(
final PrintJobStatus metadata, final HttpServletResponse httpServletResponse,
final ReportLoader reportLoader, final URI reportURI, final boolean inline)
throws IOException {
try (OutputStream response = httpServletResponse.getOutputStream()) {
httpServletResponse.setContentType(metadata.getResult().getMimeType());
if (!inline) {
String fileName = metadata.getResult().getFileName();
Matcher matcher = VARIABLE_PATTERN.matcher(fileName);
while (matcher.find()) {
final String variable = matcher.group(1);
String replacement = findReplacement(variable, metadata.getCompletionDate());
fileName = fileName.replace("${" + variable + "}", replacement);
matcher = VARIABLE_PATTERN.matcher(fileName);
}
fileName += "." + metadata.getResult().getFileExtension();
httpServletResponse
.setHeader("Content-disposition", "attachment; filename=" + cleanUpName(fileName));
}
reportLoader.loadReport(reportURI, response);
}
}
private void addDownloadLinkToJson(
final HttpServletRequest httpServletRequest, final String ref,
final JSONWriter json) {
String downloadURL = getBaseUrl(httpServletRequest) + REPORT_URL + "/" + ref;
json.key(JSON_DOWNLOAD_LINK).value(downloadURL);
}
/**
* Read the headers from the request.
*
* @param httpServletRequest the request object
*/
protected final JSONObject getHeaders(final HttpServletRequest httpServletRequest) {
@SuppressWarnings("rawtypes")
Enumeration headersName = httpServletRequest.getHeaderNames();
JSONObject headers = new JSONObject();
while (headersName.hasMoreElements()) {
String name = headersName.nextElement().toString();
Enumeration<String> e = httpServletRequest.getHeaders(name);
while (e.hasMoreElements()) {
headers.append(name, e.nextElement());
}
}
final JSONObject requestHeadersAttribute = new JSONObject();
requestHeadersAttribute.put(JSON_REQUEST_HEADERS, headers);
return requestHeadersAttribute;
}
/**
* Start a print job.
*
* @param appId the id of the printer app
* @param format the format of the returned report.
* @param requestDataRaw the request json in string form
* @param httpServletRequest the request object
* @param httpServletResponse the response object
* @return the job reference id
*/
private String createAndSubmitPrintJob(
final String appId, final String format, final String requestDataRaw,
final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse)
throws NoSuchAppException {
PJsonObject specJson = parseJson(requestDataRaw, httpServletResponse);
if (specJson == null) {
return null;
}
String ref = maybeAddRequestId(
UUID.randomUUID().toString() + "@" + this.servletInfo.getServletId(),
httpServletRequest);
MDC.put(Processor.MDC_JOB_ID_KEY, ref);
LOGGER.debug("{}", specJson);
specJson.getInternalObj().remove(JSON_OUTPUT_FORMAT);
specJson.getInternalObj().put(JSON_OUTPUT_FORMAT, format);
specJson.getInternalObj().remove(JSON_APP);
specJson.getInternalObj().put(JSON_APP, appId);
final JSONObject requestHeaders = getHeaders(httpServletRequest);
if (requestHeaders.length() > 0) {
specJson.getInternalObj().getJSONObject(JSON_ATTRIBUTES)
.put(JSON_REQUEST_HEADERS, requestHeaders);
}
// check that we have authorization and configure the job so it can only be access by users with
// sufficient authorization
final String templateName = specJson.getString(Constants.JSON_LAYOUT_KEY);
final MapPrinter mapPrinter = this.mapPrinterFactory.create(appId);
checkReferer(httpServletRequest, mapPrinter);
final Template template = mapPrinter.getConfiguration().getTemplate(templateName);
if (template == null) {
return null;
}
PrintJobEntryImpl jobEntry = new PrintJobEntryImpl(ref, specJson, System.currentTimeMillis());
jobEntry.configureAccess(template, this.context);
try {
this.jobManager.submit(jobEntry);
} catch (RuntimeException exc) {
LOGGER.error("Error when creating job on {}: {}", appId, specJson, exc);
ref = null;
}
return ref;
}
private boolean checkReferer(
final HttpServletRequest request, final MapPrinter mapPrinter) {
final Configuration config = mapPrinter.getConfiguration();
final UriMatchers allowedReferers = config.getAllowedReferersImpl();
if (allowedReferers == null) {
return true;
}
String referer = request.getHeader("referer");
if (referer == null) {
referer = "http://localhost/";
}
try {
return allowedReferers.matches(new URI(referer),
HttpMethod.resolve(request.getMethod()));
} catch (SocketException | UnknownHostException | URISyntaxException | MalformedURLException e) {
LOGGER.error("Referer {} invalid", referer, e);
return false;
}
}
private <R> R loadReport(
final String referenceId, final HttpServletResponse httpServletResponse,
final HandleReportLoadResult<R> handler) throws IOException, ServletException {
PrintJobStatus metadata;
try {
metadata = this.jobManager.getStatus(referenceId);
} catch (NoSuchReferenceException e) {
return handler.unknownReference(httpServletResponse, referenceId);
}
if (!metadata.isDone()) {
return handler.printJobPending(httpServletResponse, referenceId);
} else if (metadata.getResult() != null) {
URI pdfURI = metadata.getResult().getReportURI();
ReportLoader loader = null;
for (ReportLoader reportLoader: this.reportLoaders) {
if (reportLoader.accepts(pdfURI)) {
loader = reportLoader;
break;
}
}
if (loader == null) {
return handler.unsupportedLoader(httpServletResponse, referenceId);
} else {
return handler.successfulPrint(metadata, httpServletResponse, pdfURI, loader);
}
} else {
return handler.failedPrint(metadata, httpServletResponse);
}
}
private void setContentType(
final HttpServletResponse statusResponse,
final String jsonpCallback) {
if (StringUtils.isEmpty(jsonpCallback)) {
statusResponse.setContentType("application/json; charset=utf-8");
} else {
statusResponse.setContentType("application/javascript; charset=utf-8");
}
}
private void appendJsonpCallback(
final String jsonpCallback,
final PrintWriter writer) {
if (!StringUtils.isEmpty(jsonpCallback)) {
writer.append(jsonpCallback);
writer.append("(");
}
}
private void appendJsonpCallbackEnd(
final String jsonpCallback,
final PrintWriter writer) {
if (!StringUtils.isEmpty(jsonpCallback)) {
writer.append(");");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_4174_1 |
crossvul-java_data_good_5805_0 | /*
* Copyright 2002-2013 the original author or authors.
*
* 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 org.springframework.web.util;
/**
* Utility class for JavaScript escaping.
* Escapes based on the JavaScript 1.5 recommendation.
*
* <p>Reference:
* <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#String_literals">
* JavaScript Guide</a> on Mozilla Developer Network.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rossen Stoyanchev
* @since 1.1.1
*/
public class JavaScriptUtils {
/**
* Turn JavaScript special characters into escaped characters.
*
* @param input the input string
* @return the string with escaped characters
*/
public static String javaScriptEscape(String input) {
if (input == null) {
return input;
}
StringBuilder filtered = new StringBuilder(input.length());
char prevChar = '\u0000';
char c;
for (int i = 0; i < input.length(); i++) {
c = input.charAt(i);
if (c == '"') {
filtered.append("\\\"");
}
else if (c == '\'') {
filtered.append("\\'");
}
else if (c == '\\') {
filtered.append("\\\\");
}
else if (c == '/') {
filtered.append("\\/");
}
else if (c == '\t') {
filtered.append("\\t");
}
else if (c == '\n') {
if (prevChar != '\r') {
filtered.append("\\n");
}
}
else if (c == '\r') {
filtered.append("\\n");
}
else if (c == '\f') {
filtered.append("\\f");
}
else if (c == '\b') {
filtered.append("\\b");
}
// No '\v' in Java, use octal value for VT ascii char
else if (c == '\013') {
filtered.append("\\v");
}
else if (c == '<') {
filtered.append("\\u003C");
}
else if (c == '>') {
filtered.append("\\u003E");
}
// Unicode for PS (line terminator in ECMA-262)
else if (c == '\u2028') {
filtered.append("\\u2028");
}
// Unicode for LS (line terminator in ECMA-262)
else if (c == '\u2029') {
filtered.append("\\u2029");
}
else {
filtered.append(c);
}
prevChar = c;
}
return filtered.toString();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_5805_0 |
crossvul-java_data_good_3049_17 | package hudson.model;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import hudson.markup.MarkupFormatter;
import java.io.IOException;
import java.io.Writer;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpStatus;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
/**
* @author huybrechts
*/
public class ParametersTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Rule
public ErrorCollector collector = new ErrorCollector();
@Test
public void parameterTypes() throws Exception {
FreeStyleProject otherProject = j.createFreeStyleProject();
otherProject.scheduleBuild2(0).get();
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"),
new BooleanParameterDefinition("boolean", true, "boolean description"),
new ChoiceParameterDefinition("choice", "Choice 1\nChoice 2", "choice description"),
new RunParameterDefinition("run", otherProject.getName(), "run description", null));
project.addProperty(pdp);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='string']");
assertNotNull(element);
assertEquals("string description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
HtmlTextInput stringParameterInput = (HtmlTextInput) DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
assertEquals("defaultValue", stringParameterInput.getAttribute("value"));
assertEquals("string", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
stringParameterInput.setAttribute("value", "newValue");
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='boolean']");
assertNotNull(element);
assertEquals("boolean description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
Object o = DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
System.out.println(o);
HtmlCheckBoxInput booleanParameterInput = (HtmlCheckBoxInput) o;
assertEquals(true, booleanParameterInput.isChecked());
assertEquals("boolean", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='run']");
assertNotNull(element);
assertEquals("run description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("run", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertEquals("newValue", builder.getEnvVars().get("STRING"));
assertEquals("true", builder.getEnvVars().get("BOOLEAN"));
assertEquals("Choice 1", builder.getEnvVars().get("CHOICE"));
assertEquals(j.jenkins.getRootUrl() + otherProject.getLastBuild().getUrl(), builder.getEnvVars().get("RUN"));
}
@Test
public void choiceWithLTGT() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new ChoiceParameterDefinition("choice", "Choice 1\nChoice <2>", "choice description"));
project.addProperty(pdp);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
HtmlOption opt = (HtmlOption)DomNodeUtil.selectSingleNode(element, "td/div/select/option[@value='Choice <2>']");
assertNotNull(opt);
assertEquals("Choice <2>", opt.asText());
opt.setSelected(true);
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertNotNull(builder.getEnvVars());
assertEquals("Choice <2>", builder.getEnvVars().get("CHOICE"));
}
@Test
public void sensitiveParameters() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new PasswordParameterDefinition("password", "12345", "password description"));
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertTrue(sensitiveVars.contains("password"));
}
@Test
public void nonSensitiveParameters() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"));
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertFalse(sensitiveVars.contains("string"));
}
@Test
public void mixedSensitivity() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"),
new PasswordParameterDefinition("password", "12345", "password description"),
new StringParameterDefinition("string2", "Value2", "string description")
);
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertFalse(sensitiveVars.contains("string"));
assertTrue(sensitiveVars.contains("password"));
assertFalse(sensitiveVars.contains("string2"));
}
@Test
@Issue("JENKINS-3539")
public void fileParameterNotSet() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new FileParameterDefinition("filename", "description"));
project.addProperty(pdp);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertFalse("file must not exist", project.getSomeWorkspace().child("filename").exists());
}
@Test
@Issue("JENKINS-11543")
public void unicodeParametersArePresetCorrectly() throws Exception {
final FreeStyleProject p = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("sname:a¶‱ﻷ", "svalue:a¶‱ﻷ", "sdesc:a¶‱ﻷ"),
new FileParameterDefinition("fname:a¶‱ﻷ", "fdesc:a¶‱ﻷ")
);
p.addProperty(pdb);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); // Ignore 405
HtmlPage page = wc.getPage(p, "build");
// java.lang.IllegalArgumentException: No such parameter definition: <gibberish>.
wc.getOptions().setThrowExceptionOnFailingStatusCode(true);
final HtmlForm form = page.getFormByName("parameters");
HtmlFormUtil.submit(form, HtmlFormUtil.getButtonByCaption(form, "Build"));
}
@Issue("SECURITY-353")
@Test
public void xss() throws Exception {
j.jenkins.setMarkupFormatter(new MyMarkupFormatter());
FreeStyleProject p = j.createFreeStyleProject("p");
StringParameterDefinition param = new StringParameterDefinition("<param name>", "<param default>", "<param description>");
assertEquals("<b>[</b>param description<b>]</b>", param.getFormattedDescription());
p.addProperty(new ParametersDefinitionProperty(param));
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.getPage(p, "build?delay=0sec");
collector.checkThat(page.getWebResponse().getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); // 405 to dissuade scripts from thinking this triggered the build
String text = page.getWebResponse().getContentAsString();
collector.checkThat("build page should escape param name", text, containsString("<param name>"));
collector.checkThat("build page should not leave param name unescaped", text, not(containsString("<param name>")));
collector.checkThat("build page should escape param default", text, containsString("<param default>"));
collector.checkThat("build page should not leave param default unescaped", text, not(containsString("<param default>")));
collector.checkThat("build page should mark up param description", text, containsString("<b>[</b>param description<b>]</b>"));
collector.checkThat("build page should not leave param description unescaped", text, not(containsString("<param description>")));
HtmlForm form = page.getFormByName("parameters");
HtmlTextInput value = form.getInputByValue("<param default>");
value.setText("<param value>");
j.submit(form);
j.waitUntilNoActivity();
FreeStyleBuild b = p.getBuildByNumber(1);
page = j.createWebClient().getPage(b, "parameters/");
text = page.getWebResponse().getContentAsString();
collector.checkThat("parameters page should escape param name", text, containsString("<param name>"));
collector.checkThat("parameters page should not leave param name unescaped", text, not(containsString("<param name>")));
collector.checkThat("parameters page should escape param value", text, containsString("<param value>"));
collector.checkThat("parameters page should not leave param value unescaped", text, not(containsString("<param value>")));
collector.checkThat("parameters page should mark up param description", text, containsString("<b>[</b>param description<b>]</b>"));
collector.checkThat("parameters page should not leave param description unescaped", text, not(containsString("<param description>")));
}
static class MyMarkupFormatter extends MarkupFormatter {
@Override
public void translate(String markup, Writer output) throws IOException {
Matcher m = Pattern.compile("[<>]").matcher(markup);
StringBuffer buf = new StringBuffer();
while (m.find()) {
m.appendReplacement(buf, m.group().equals("<") ? "<b>[</b>" : "<b>]</b>");
}
m.appendTail(buf);
output.write(buf.toString());
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_3049_17 |
crossvul-java_data_good_509_0 | package org.hswebframework.web.workflow.enums;
/**
* @author zhouhao
* @since 3.0.5
*/
public enum ModelType {
bpmn, json
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_509_0 |
crossvul-java_data_bad_1166_0 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.context;
import com.sun.faces.component.visit.PartialVisitContext;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitHint;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;
import java.io.Writer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;
import javax.faces.FactoryFinder;
import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.component.visit.VisitContextWrapper;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
public class PartialViewContextImpl extends PartialViewContext {
// Log instance for this class
private static Logger LOGGER = FacesLogger.CONTEXT.getLogger();
private boolean released;
// BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD
private PartialResponseWriter partialResponseWriter;
private List<String> executeIds;
private Collection<String> renderIds;
private Boolean ajaxRequest;
private Boolean partialRequest;
private Boolean renderAll;
private FacesContext ctx;
private boolean processingPhases = false;
private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER";
// ----------------------------------------------------------- Constructors
public PartialViewContextImpl(FacesContext ctx) {
this.ctx = ctx;
}
// ---------------------------------------------- Methods from PartialViewContext
/**
* @see javax.faces.context.PartialViewContext#isAjaxRequest()
*/
@Override
public boolean isAjaxRequest() {
assertNotReleased();
if (ajaxRequest == null) {
ajaxRequest = "partial/ajax".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
if (!ajaxRequest) {
ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap().
get("Faces-Request"));
}
}
return ajaxRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isPartialRequest()
*/
@Override
public boolean isPartialRequest() {
assertNotReleased();
if (partialRequest == null) {
partialRequest = isAjaxRequest() ||
"partial/process".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
}
return partialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isExecuteAll()
*/
@Override
public boolean isExecuteAll() {
assertNotReleased();
String execute = ctx.
getExternalContext().getRequestParameterMap()
.get(PARTIAL_EXECUTE_PARAM_NAME);
return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute));
}
/**
* @see javax.faces.context.PartialViewContext#isRenderAll()
*/
@Override
public boolean isRenderAll() {
assertNotReleased();
if (renderAll == null) {
String render = ctx.
getExternalContext().getRequestParameterMap()
.get(PARTIAL_RENDER_PARAM_NAME);
renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render));
}
return renderAll;
}
/**
* @see javax.faces.context.PartialViewContext#setRenderAll(boolean)
*/
@Override
public void setRenderAll(boolean renderAll) {
this.renderAll = renderAll;
}
@Override
public boolean isResetValues() {
Object value = ctx.getExternalContext().getRequestParameterMap().get(RESET_VALUES_PARAM_NAME);
return (null != value && "true".equals(value)) ? true : false;
}
@Override
public void setPartialRequest(boolean isPartialRequest) {
this.partialRequest = isPartialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#getExecuteIds()
*/
@Override
public Collection<String> getExecuteIds() {
assertNotReleased();
if (executeIds != null) {
return executeIds;
}
executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM_NAME);
// include the view parameter facet ID if there are other execute IDs
// to process
if (!executeIds.isEmpty()) {
UIViewRoot root = ctx.getViewRoot();
if (root.getFacetCount() > 0) {
if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) {
executeIds.add(0, UIViewRoot.METADATA_FACET_NAME);
}
}
}
return executeIds;
}
/**
* @see javax.faces.context.PartialViewContext#getRenderIds()
*/
@Override
public Collection<String> getRenderIds() {
assertNotReleased();
if (renderIds != null) {
return renderIds;
}
renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM_NAME);
return renderIds;
}
/**
* @see PartialViewContext#processPartial(javax.faces.event.PhaseId)
*/
@Override
public void processPartial(PhaseId phaseId) {
PartialViewContext pvc = ctx.getPartialViewContext();
Collection <String> myExecuteIds = pvc.getExecuteIds();
Collection <String> myRenderIds = pvc.getRenderIds();
UIViewRoot viewRoot = ctx.getViewRoot();
if (phaseId == PhaseId.APPLY_REQUEST_VALUES ||
phaseId == PhaseId.PROCESS_VALIDATIONS ||
phaseId == PhaseId.UPDATE_MODEL_VALUES) {
// Skip this processing if "none" is specified in the render list,
// or there were no execute phase client ids.
if (myExecuteIds == null || myExecuteIds.isEmpty()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"No execute and render identifiers specified. Skipping component processing.");
}
return;
}
try {
processComponents(viewRoot, phaseId, myExecuteIds, ctx);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO,
e.toString(),
e);
}
throw new FacesException(e);
}
// If we have just finished APPLY_REQUEST_VALUES phase, install the
// partial response writer. We want to make sure that any content
// or errors generated in the other phases are written using the
// partial response writer.
//
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ctx.setResponseWriter(writer);
}
} else if (phaseId == PhaseId.RENDER_RESPONSE) {
try {
//
// We re-enable response writing.
//
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ResponseWriter orig = ctx.getResponseWriter();
ctx.getAttributes().put(ORIGINAL_WRITER, orig);
ctx.setResponseWriter(writer);
ExternalContext exContext = ctx.getExternalContext();
exContext.setResponseContentType("text/xml");
exContext.addResponseHeader("Cache-Control", "no-cache");
// String encoding = writer.getCharacterEncoding( );
// if( encoding == null ) {
// encoding = "UTF-8";
// }
// writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n");
writer.startDocument();
if (isResetValues()) {
viewRoot.resetValues(ctx, myRenderIds);
}
if (isRenderAll()) {
renderAll(ctx, viewRoot);
renderState(ctx);
writer.endDocument();
return;
}
// Skip this processing if "none" is specified in the render list,
// or there were no render phase client ids.
if (myRenderIds != null && !myRenderIds.isEmpty()) {
processComponents(viewRoot, phaseId, myRenderIds, ctx);
}
renderState(ctx);
writer.endDocument();
} catch (IOException ex) {
this.cleanupAfterView();
} catch (RuntimeException ex) {
this.cleanupAfterView();
// Throw the exception
throw ex;
}
}
}
/**
* @see javax.faces.context.PartialViewContext#getPartialResponseWriter()
*/
@Override
public PartialResponseWriter getPartialResponseWriter() {
assertNotReleased();
if (partialResponseWriter == null) {
partialResponseWriter = new DelayedInitPartialResponseWriter(this);
}
return partialResponseWriter;
}
/**
* @see javax.faces.context.PartialViewContext#release()
*/
public void release() {
released = true;
ajaxRequest = null;
renderAll = null;
partialResponseWriter = null;
executeIds = null;
renderIds = null;
ctx = null;
partialRequest = null;
}
// -------------------------------------------------------- Private Methods
private List<String> populatePhaseClientIds(String parameterName) {
Map<String,String> requestParamMap =
ctx.getExternalContext().getRequestParameterMap();
String param = requestParamMap.get(parameterName);
if (param == null) {
return new ArrayList<String>();
} else {
Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
String[] pcs = Util.split(appMap, param, "[ \t]+");
return ((pcs != null && pcs.length != 0)
? new ArrayList<String>(Arrays.asList(pcs))
: new ArrayList<String>());
}
}
// Process the components specified in the phaseClientIds list
private void processComponents(UIComponent component, PhaseId phaseId,
Collection<String> phaseClientIds, FacesContext context) throws IOException {
// We use the tree visitor mechanism to locate the components to
// process. Create our (partial) VisitContext and the
// VisitCallback that will be invoked for each component that
// is visited. Note that we use the SKIP_UNRENDERED hint as we
// only want to visit the rendered subtree.
EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE);
VisitContextFactory visitContextFactory = (VisitContextFactory)
FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY);
VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints);
PhaseAwareVisitCallback visitCallback =
new PhaseAwareVisitCallback(ctx, phaseId);
component.visitTree(visitContext, visitCallback);
PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext);
if (partialVisitContext != null) {
if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) {
Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds();
String message;
StringBuilder builder = new StringBuilder();
for (String cur : unvisitedClientIds) {
builder.append(cur).append(" ");
}
LOGGER.log(Level.FINER,
"jsf.context.partial_visit_context_unvisited_children",
new Object[]{builder.toString()});
}
}
}
/**
* Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s.
*
* If no {@link PartialVisitContext} is found in the chain, null is returned instead.
*
* @param visitContext the visit context.
* @return the (unwrapped) partial visit context.
*/
private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) {
if (visitContext == null) {
return null;
}
if (visitContext instanceof PartialVisitContext) {
return (PartialVisitContext) visitContext;
}
if (visitContext instanceof VisitContextWrapper) {
return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped());
}
return null;
}
private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException {
// If this is a "render all via ajax" request,
// make sure to wrap the entire page in a <render> elemnt
// with the special viewStateId of VIEW_ROOT_ID. This is how the client
// JavaScript knows how to replace the entire document with
// this response.
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
if (!Util.isPortletRequest(context)) {
writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
writer.endUpdate();
}
else {
/*
* If we have a portlet request, start rendering at the view root.
*/
writer.startUpdate(viewRoot.getClientId(ctx));
viewRoot.encodeBegin(context);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
viewRoot.encodeEnd(context);
writer.endUpdate();
}
}
private void renderState(FacesContext context) throws IOException {
// Get the view state and write it to the response..
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
String viewStateId = Util.getViewStateId(context);
writer.startUpdate(viewStateId);
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
writer.endUpdate();
ClientWindow window = context.getExternalContext().getClientWindow();
if (null != window) {
String clientWindowId = Util.getClientWindowId(context);
writer.startUpdate(clientWindowId);
writer.write(window.getId());
writer.endUpdate();
}
}
private PartialResponseWriter createPartialResponseWriter() {
ExternalContext extContext = ctx.getExternalContext();
String encoding = extContext.getRequestCharacterEncoding();
extContext.setResponseCharacterEncoding(encoding);
ResponseWriter responseWriter = null;
Writer out = null;
try {
out = extContext.getResponseOutputWriter();
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
}
if (out != null) {
UIViewRoot viewRoot = ctx.getViewRoot();
if (viewRoot != null) {
responseWriter =
ctx.getRenderKit().createResponseWriter(out,
"text/xml", encoding);
} else {
RenderKitFactory factory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);
responseWriter = renderKit.createResponseWriter(out, "text/xml", encoding);
}
}
if (responseWriter instanceof PartialResponseWriter) {
return (PartialResponseWriter) responseWriter;
} else {
return new PartialResponseWriter(responseWriter);
}
}
private void cleanupAfterView() {
ResponseWriter orig = (ResponseWriter) ctx.getAttributes().
get(ORIGINAL_WRITER);
assert(null != orig);
// move aside the PartialResponseWriter
ctx.setResponseWriter(orig);
}
@SuppressWarnings({"FinalPrivateMethod"})
private final void assertNotReleased() {
if (released) {
throw new IllegalStateException();
}
}
// ----------------------------------------------------------- Inner Classes
private static class PhaseAwareVisitCallback implements VisitCallback {
private PhaseId curPhase;
private FacesContext ctx;
private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) {
this.ctx = ctx;
this.curPhase = curPhase;
}
public VisitResult visit(VisitContext context, UIComponent comp) {
try {
if (curPhase == PhaseId.APPLY_REQUEST_VALUES) {
// RELEASE_PENDING handle immediate request(s)
// If the user requested an immediate request
// Make sure to set the immediate flag here.
comp.processDecodes(ctx);
} else if (curPhase == PhaseId.PROCESS_VALIDATIONS) {
comp.processValidators(ctx);
} else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) {
comp.processUpdates(ctx);
} else if (curPhase == PhaseId.RENDER_RESPONSE) {
PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter();
writer.startUpdate(comp.getClientId(ctx));
// do the default behavior...
comp.encodeAll(ctx);
writer.endUpdate();
} else {
throw new IllegalStateException("I18N: Unexpected " +
"PhaseId passed to " +
" PhaseAwareContextCallback: " +
curPhase.toString());
}
}
catch (IOException ex) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe(ex.toString());
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ex.toString(),
ex);
}
throw new FacesException(ex);
}
// Once we visit a component, there is no need to visit
// its children, since processDecodes/Validators/Updates and
// encodeAll() already traverse the subtree. We return
// VisitResult.REJECT to supress the subtree visit.
return VisitResult.REJECT;
}
}
/**
* Delays the actual construction of the PartialResponseWriter <em>until</em>
* content is going to actually be written.
*/
private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter {
private ResponseWriter writer;
private PartialViewContextImpl ctx;
// -------------------------------------------------------- Constructors
public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) {
super(null);
this.ctx = ctx;
ExternalContext extCtx = ctx.ctx.getExternalContext();
extCtx.setResponseContentType("text/xml");
extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding());
}
// ---------------------------------- Methods from PartialResponseWriter
@Override
public ResponseWriter getWrapped() {
if (writer == null) {
writer = ctx.createPartialResponseWriter();
}
return writer;
}
} // END DelayedInitPartialResponseWriter
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_1166_0 |
crossvul-java_data_bad_1166_1 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.lifecycle;
import java.util.Map;
import java.util.regex.Pattern;
import javax.faces.component.UINamingContainer;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.ResponseStateManager;
import javax.faces.FacesException;
public class ClientWindowImpl extends ClientWindow {
String id;
public ClientWindowImpl() {
}
@Override
public Map<String, String> getQueryURLParameters(FacesContext context) {
return null;
}
@Override
public void decode(FacesContext context) {
Map<String, String> requestParamMap = context.getExternalContext().getRequestParameterMap();
if (isClientWindowRenderModeEnabled(context)) {
id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_URL_PARAM);
}
// The hidden field always takes precedence, if present.
if (requestParamMap.containsKey(ResponseStateManager.CLIENT_WINDOW_PARAM)) {
id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_PARAM);
Pattern safePattern = Pattern.compile(".*<(.*:script|script).*>[^&]*</\\s*\\1\\s*>.*");
if (safePattern.matcher(id).matches()) {
throw new FacesException("ClientWindow is illegal: " + id);
}
}
if (null == id) {
id = calculateClientWindow(context);
}
}
private String calculateClientWindow(FacesContext context) {
synchronized(context.getExternalContext().getSession(true)) {
final String clientWindowCounterKey = "com.sun.faces.lifecycle.ClientWindowCounterKey";
ExternalContext extContext = context.getExternalContext();
Map<String, Object> sessionAttrs = extContext.getSessionMap();
Integer counter = (Integer) sessionAttrs.get(clientWindowCounterKey);
if (null == counter) {
counter = Integer.valueOf(0);
}
char sep = UINamingContainer.getSeparatorChar(context);
id = extContext.getSessionId(true) + sep +
+ counter;
sessionAttrs.put(clientWindowCounterKey, ++counter);
}
return id;
}
@Override
public String getId() {
return id;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_1166_1 |
crossvul-java_data_good_4990_0 | /**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.common.localization;
import java.text.Collator;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.conf.ConfigDefaults;
import com.redhat.rhn.common.db.datasource.DataResult;
import com.redhat.rhn.common.db.datasource.ModeFactory;
import com.redhat.rhn.common.db.datasource.SelectMode;
import com.redhat.rhn.common.util.StringUtil;
import com.redhat.rhn.frontend.context.Context;
/**
* Localization service class to simplify the job for producing localized
* (translated) strings within the product.
*
* @version $Rev$
*/
public class LocalizationService {
/**
* DateFormat used by RHN database queries. Useful for converting RHN dates
* into java.util.Dates so they can be formatted based on Locale.
*/
public static final String RHN_DB_DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String RHN_CUSTOM_DATEFORMAT = "yyyy-MM-dd HH:mm:ss z";
private static Logger log = Logger.getLogger(LocalizationService.class);
private static Logger msgLogger = Logger
.getLogger("com.redhat.rhn.common.localization.messages");
public static final Locale DEFAULT_LOCALE = new Locale("EN", "US");
// private instance of the service.
private static LocalizationService instance = new LocalizationService();
// This Map stores the association of the java class names
// that map to the message keys found in the StringResources.xml
// files. This allows us to have sets of XML ResourceBundles that
// are specified in the rhn.jconf
private Map<String, String> keyToBundleMap;
// List of supported locales
private final Map<String, LocaleInfo> supportedLocales =
new HashMap<String, LocaleInfo>();
/**
* hidden constructor
*/
private LocalizationService() {
initService();
}
/**
* Initialize the set of strings and keys used by the service
*/
protected void initService() {
// If we are reloading, lets log it.
if (keyToBundleMap != null) {
// We want to note in the log that we are doing this
log.warn("Reloading XML StringResource files.");
XmlMessages.getInstance().resetBundleCache();
}
keyToBundleMap = new HashMap<String, String>();
// Get the list of configured classnames from the config file.
String[] packages = Config.get().getStringArray(
ConfigDefaults.WEB_L10N_RESOURCEBUNDLES);
for (int i = 0; i < packages.length; i++) {
addKeysToMap(packages[i]);
}
if (supportedLocales.size() > 0) {
supportedLocales.clear();
}
loadSupportedLocales();
}
/** Add the keys from the specified class to the Service's Map. */
private void addKeysToMap(String className) {
try {
Class z = Class.forName(className);
// All the keys must exist in the en_US XML files first. The other
// languages may have subsets but no unique keys. If this is a
// problem
// refactoring will need to take place.
Enumeration<String> e = XmlMessages.getInstance().getKeys(z, Locale.US);
while (e.hasMoreElements()) {
String key = e.nextElement();
keyToBundleMap.put(key, className);
}
}
catch (ClassNotFoundException ce) {
String message = "Class not found when trying to initalize " +
"the LocalizationService: " + ce.toString();
log.error(message, ce);
throw new LocalizationException(message, ce);
}
}
private void loadSupportedLocales() {
String rawLocales = Config.get().getString("java.supported_locales");
if (rawLocales == null) {
return;
}
List<String> compoundLocales = new LinkedList<String>();
for (Enumeration<Object> locales = new StringTokenizer(rawLocales, ","); locales
.hasMoreElements();) {
String locale = (String) locales.nextElement();
if (locale.indexOf('_') > -1) {
compoundLocales.add(locale);
}
LocaleInfo li = new LocaleInfo(locale);
this.supportedLocales.put(locale, li);
}
for (Iterator<String> iter = compoundLocales.iterator(); iter.hasNext();) {
String cl = iter.next();
String[] parts = cl.split("_");
LocaleInfo li = new LocaleInfo(parts[0], cl);
if (this.supportedLocales.get(parts[0]) == null) {
this.supportedLocales.put(parts[0], li);
}
}
}
/**
* Get the running instance of the LocalizationService
*
* @return The LocalizationService singleton
*/
public static LocalizationService getInstance() {
return instance;
}
/**
* Reload the resource files from the disk. Only works in development mode.
* @return boolean if we reloaded the files or not.
*/
public boolean reloadResourceFiles() {
if (Config.get().getBoolean("java.development_environment")) {
initService();
return true;
}
log.error("Tried to reload XML StringResource files but " +
"we aren't in java.development_environment mode");
return false;
}
/**
* Get a localized version of a String and let the service attempt to figure
* out the callee's locale.
* @param messageId The key of the message we are fetching
* @return Translated String
*/
public String getMessage(String messageId) {
Context ctx = Context.getCurrentContext();
return getMessage(messageId, ctx.getLocale(), new Object[0]);
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param locale The locale to use when fetching the string
* @return Translated String
*/
public String getMessage(String messageId, Locale locale) {
return getMessage(messageId, locale, new Object[0]);
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param args arguments for message.
* @return Translated String
*/
public String getMessage(String messageId, Object... args) {
Context ctx = Context.getCurrentContext();
return getMessage(messageId, ctx.getLocale(), args);
}
/**
* Gets a Plain Text + localized version of a string with the default locale.
* @param messageId The key of the message we are fetching
* @param args arguments for message.
* @return Translated String
*/
public String getPlainText(String messageId, Object... args) {
String msg = getMessage(messageId, args);
String unescaped = StringEscapeUtils.unescapeHtml(msg);
return StringUtil.toPlainText(unescaped);
}
/**
* Gets a Plain Text + localized version of a string with the default locale.
* @param messageId The key of the message we are fetching
* @return Translated String
*/
public String getPlainText(String messageId) {
return getPlainText(messageId, (Object[])null);
}
/**
* Take in a String array of keys and transform it into a String array of
* localized Strings.
* @param keys String[] array of key values
* @return String[] array of localized strings.
*/
public String[] getMessages(String[] keys) {
String[] retval = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
retval[i] = getMessage(keys[i]);
}
return retval;
}
/**
* Get a localized version of a string with the specified locale.
* @param messageId The key of the message we are fetching
* @param locale The locale to use when fetching the string
* @param args arguments for message.
* @return Translated String
*/
public String getMessage(String messageId, Locale locale, Object... args) {
log.debug("getMessage() called with messageId: " + messageId +
" and locale: " + locale);
// Short-circuit the rest of the method if the messageId is null
// See bz 199892
if (messageId == null) {
return getMissingMessageString(messageId);
}
String userLocale = locale == null ? "null" : locale.toString();
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId +
"\" for locale " + userLocale);
}
String mess = null;
Class z = null;
try {
// If the keyMap doesn't contain the requested key
// then there is no hope and we return.
if (!keyToBundleMap.containsKey(messageId)) {
return getMissingMessageString(messageId);
}
z = Class.forName(keyToBundleMap.get(messageId));
// If we already determined that there aren't an bundles
// for this Locale then we shouldn't repeatedly fail
// attempts to parse the bundle. Instead just force a
// call to the default Locale.
mess = XmlMessages.getInstance().format(z, locale,
messageId, args);
}
catch (MissingResourceException e) {
// Try again with DEFAULT_LOCALE
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId +
"\" for locale " + userLocale +
" failed - trying again with default " + "locale " +
DEFAULT_LOCALE.toString());
}
try {
mess = XmlMessages.getInstance().format(z, DEFAULT_LOCALE,
messageId, args);
}
catch (MissingResourceException mre) {
if (msgLogger.isDebugEnabled()) {
msgLogger.debug("Resolving message \"" + messageId + "\" " +
"for default locale " + DEFAULT_LOCALE.toString() +
" failed");
}
return getMissingMessageString(messageId);
}
}
catch (ClassNotFoundException ce) {
String message = "Class not found when trying to fetch a message: " +
ce.toString();
log.error(message, ce);
throw new LocalizationException(message, ce);
}
return getDebugVersionOfString(mess);
}
private String getDebugVersionOfString(String mess) {
// If we have put the Service into debug mode we
// will wrap all the messages in a marker.
boolean debugMode = Config.get().getBoolean("java.l10n_debug");
if (debugMode) {
StringBuilder debug = new StringBuilder();
String marker = Config.get().getString("java.l10n_debug_marker",
"$$$");
debug.append(marker);
debug.append(mess);
debug.append(marker);
mess = debug.toString();
}
return mess;
}
// returns the first class/method that does not belong to this
// package (who calls this actually) - for debugging purposes
private StackTraceElement getCallingMethod() {
try {
throw new RuntimeException("Stacktrace Dummy Exception");
}
catch (RuntimeException e) {
try {
final String prefix = this.getClass().getPackage().getName();
for (StackTraceElement element : e.getStackTrace()) {
if (!element.getClassName().startsWith(prefix)) {
return element;
}
}
}
catch (Throwable t) {
// dont break - return nothing rather than stop
return null;
}
}
return null;
}
private String getMissingMessageString(String messageId) {
String caller = "";
StackTraceElement callerElement = getCallingMethod();
if (callerElement != null) {
caller = " called by " + callerElement;
}
if (messageId == null) {
messageId = "null";
}
String message = "*** ERROR: Message with id: [" + messageId +
"] not found.***" + caller;
log.error(message);
boolean exceptionMode = Config.get().getBoolean(
"java.l10n_missingmessage_exceptions");
if (exceptionMode) {
throw new IllegalArgumentException(message);
}
return StringEscapeUtils.escapeHtml("**" + messageId + "**");
}
/**
* Get localized text for log messages as well as error emails. Determines
* Locale of running JVM vs using the current Thread or any other User
* related Locale information. TODO mmccune Get Locale out of Config or from
* the JVM
* @param messageId The key of the message we are fetching
* @return String debug message.
*/
public String getDebugMessage(String messageId) {
return getMessage(messageId, Locale.US);
}
/**
* Format the date and let the service determine the locale
* @param date Date to be formatted.
* @return String representation of given date.
*/
public String formatDate(Date date) {
Context ctx = Context.getCurrentContext();
return formatDate(date, ctx.getLocale());
}
/**
* Format the date as a short date depending on locale (YYYY-MM-DD in the
* US)
* @param date Date to be formatted
* @return String representation of given date.
*/
public String formatShortDate(Date date) {
Context ctx = Context.getCurrentContext();
return formatShortDate(date, ctx.getLocale());
}
/**
* Format the date as a short date depending on locale (YYYY-MM-DD in the
* US)
*
* @param date Date to be formatted
* @param locale Locale to use for formatting
* @return String representation of given date.
*/
public String formatShortDate(Date date, Locale locale) {
StringBuilder dbuff = new StringBuilder();
DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
dbuff.append(dateI.format(date));
return getDebugVersionOfString(dbuff.toString());
}
/**
* Use today's date and get it back localized and as a String
* @return String representation of today's date.
*/
public String getBasicDate() {
return formatDate(new Date());
}
/**
* Format the date based on the locale and convert it to a String to
* display. Uses DateFormat.SHORT. Example: 2004-12-10 13:20:00 PST
*
* Also includes the timezone of the current User if there is one
*
* @param date Date to format.
* @param locale Locale to use for formatting.
* @return String representation of given date in given locale.
*/
public String formatDate(Date date, Locale locale) {
// Example: 2004-12-10 13:20:00 PST
StringBuilder dbuff = new StringBuilder();
DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
dateI.setTimeZone(determineTimeZone());
DateFormat timeI = DateFormat.getTimeInstance(DateFormat.LONG, locale);
timeI.setTimeZone(determineTimeZone());
dbuff.append(dateI.format(date));
dbuff.append(" ");
dbuff.append(timeI.format(date));
return getDebugVersionOfString(dbuff.toString());
}
/**
* Returns fixed custom format string displayed for the determined timezone
* Example: 2010-04-01 15:04:24 CEST
*
* @param date Date to format.
* @return String representation of given date for set timezone
*/
public String formatCustomDate(Date date) {
TimeZone tz = determineTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat(RHN_CUSTOM_DATEFORMAT);
sdf.setTimeZone(tz);
return sdf.format(date);
}
/**
* Format the Number based on the locale and convert it to a String to
* display.
* @param numberIn Number to format.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn) {
Context ctx = Context.getCurrentContext();
return formatNumber(numberIn, ctx.getLocale());
}
/**
* Format the Number based on the locale and convert it to a String to
* display. Use a specified number of fraction digits.
* @param numberIn Number to format.
* @param fractionalDigits The number of fractional digits to use. This is
* both the minimum and maximum that will be displayed.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, int fractionalDigits) {
Context ctx = Context.getCurrentContext();
return formatNumber(numberIn, ctx.getLocale(), fractionalDigits);
}
/**
* Format the Number based on the locale and convert it to a String to
* display.
* @param numberIn Number to format.
* @param localeIn Locale to use for formatting.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, Locale localeIn) {
return getDebugVersionOfString(NumberFormat.getInstance(localeIn)
.format(numberIn));
}
/**
* Format the Number based on the locale and convert it to a String to
* display. Use a specified number of fractional digits.
* @param numberIn Number to format.
* @param localeIn Locale to use for formatting.
* @param fractionalDigits The maximum number of fractional digits to use.
* @return String representation of given number in given locale.
*/
public String formatNumber(Number numberIn, Locale localeIn,
int fractionalDigits) {
NumberFormat nf = NumberFormat.getInstance(localeIn);
nf.setMaximumFractionDigits(fractionalDigits);
return getDebugVersionOfString(nf.format(numberIn));
}
/**
* Get alphabet list for callee's Thread's Locale
* @return the list of alphanumeric characters from the alphabet
*/
public List<String> getAlphabet() {
return StringUtil.stringToList(getMessage("alphabet"));
}
/**
* Get digit list for callee's Thread's Locale
* @return the list of digits
*/
public List<String> getDigits() {
return StringUtil.stringToList(getMessage("digits"));
}
/**
* Get a list of available prefixes and ensure that it is sorted by
* returning a SortedSet object.
* @return SortedSet sorted set of available prefixes.
*/
public SortedSet<String> availablePrefixes() {
SelectMode prefixMode = ModeFactory.getMode("util_queries",
"available_prefixes");
// no params for this query
DataResult<Map<String, Object>> dr = prefixMode.execute(new HashMap());
SortedSet<String> ret = new TreeSet<String>();
Iterator<Map<String, Object>> i = dr.iterator();
while (i.hasNext()) {
Map<String, Object> row = i.next();
ret.add((String) row.get("prefix"));
}
return ret;
}
/**
* Get a SortedMap containing NAME/CODE value pairs. The reason we key the
* Map based on the NAME is that we desire to maintain a localized sort
* order based on the display value and not the code.
*
* <pre>
* {name=Spain, code=ES}
* {name=Sri Lanka, code=LK}
* {name=Sudan, code=SD}
* {name=Suriname, code=SR, }
* etc ...
* </pre>
*
* @return SortedMap sorted map of available countries.
*/
public SortedMap<String, String> availableCountries() {
List<String> validCountries = new LinkedList<String>(
Arrays.asList(Locale
.getISOCountries()));
String[] excluded = Config.get().getStringArray(
ConfigDefaults.WEB_EXCLUDED_COUNTRIES);
if (excluded != null) {
validCountries.removeAll(new LinkedList<String>(Arrays
.asList(excluded)));
}
SortedMap<String, String> ret = new TreeMap<String, String>();
for (Iterator<String> iter = validCountries.iterator(); iter.hasNext();) {
String isoCountry = iter.next();
ret.put(this.getMessage(isoCountry), isoCountry);
}
return ret;
}
/**
* Simple util method to determine if the
* @param messageId we are searching for
* @return boolean if we have loaded this message
*/
public boolean hasMessage(String messageId) {
return this.keyToBundleMap.containsKey(messageId);
}
/**
* Get list of supported locales in string form
* @return supported locales
*/
public List<String> getSupportedLocales() {
List<String> tmp = new LinkedList<String>(this.supportedLocales.keySet());
Collections.sort(tmp);
return Collections.unmodifiableList(tmp);
}
/**
* Returns the list of configured locales which is most likely a subset of
* all the supported locales
* @return list of configured locales
*/
public List<String> getConfiguredLocales() {
List<String> tmp = new LinkedList<String>();
for (Iterator<String> iter = this.supportedLocales.keySet().iterator(); iter
.hasNext();) {
String key = iter.next();
LocaleInfo li = this.supportedLocales.get(key);
if (!li.isAlias()) {
tmp.add(key);
}
}
Collections.sort(tmp);
return Collections.unmodifiableList(tmp);
}
/**
* Determines if locale is supported
* @param locale user's locale
* @return result
*/
public boolean isLocaleSupported(Locale locale) {
return this.supportedLocales.get(locale.toString()) != null;
}
/**
* Determine the Timezone from the Context. Uses TimeZone.getDefault() if
* there isn't one.
*
* @return TimeZone from the Context
*/
private TimeZone determineTimeZone() {
TimeZone retval = null;
Context ctx = Context.getCurrentContext();
if (ctx != null) {
retval = ctx.getTimezone();
}
if (retval == null) {
log.debug("Context is null");
// Get the app server's default timezone
retval = TimeZone.getDefault();
}
if (log.isDebugEnabled()) {
log.debug("Determined timeZone to be: " + retval);
}
return retval;
}
/**
* Returns a NEW instance of the collator/string comparator
* based on the current locale..
* Look at the javadoc for COllator to see what it does...
* (basically an i18n aware string comparator)
* @return neww instance of the collator
*/
public Collator newCollator() {
Context context = Context.getCurrentContext();
if (context != null && context.getLocale() != null) {
return Collator.getInstance(context.getLocale());
}
return Collator.getInstance();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_4990_0 |
crossvul-java_data_bad_3049_17 | package hudson.model;
import static org.junit.Assert.*;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
import org.junit.Rule;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import java.util.Set;
/**
* @author huybrechts
*/
public class ParametersTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void parameterTypes() throws Exception {
FreeStyleProject otherProject = j.createFreeStyleProject();
otherProject.scheduleBuild2(0).get();
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"),
new BooleanParameterDefinition("boolean", true, "boolean description"),
new ChoiceParameterDefinition("choice", "Choice 1\nChoice 2", "choice description"),
new RunParameterDefinition("run", otherProject.getName(), "run description", null));
project.addProperty(pdp);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='string']");
assertNotNull(element);
assertEquals("string description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
HtmlTextInput stringParameterInput = (HtmlTextInput) DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
assertEquals("defaultValue", stringParameterInput.getAttribute("value"));
assertEquals("string", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
stringParameterInput.setAttribute("value", "newValue");
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='boolean']");
assertNotNull(element);
assertEquals("boolean description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
Object o = DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
System.out.println(o);
HtmlCheckBoxInput booleanParameterInput = (HtmlCheckBoxInput) o;
assertEquals(true, booleanParameterInput.isChecked());
assertEquals("boolean", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='run']");
assertNotNull(element);
assertEquals("run description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("run", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertEquals("newValue", builder.getEnvVars().get("STRING"));
assertEquals("true", builder.getEnvVars().get("BOOLEAN"));
assertEquals("Choice 1", builder.getEnvVars().get("CHOICE"));
assertEquals(j.jenkins.getRootUrl() + otherProject.getLastBuild().getUrl(), builder.getEnvVars().get("RUN"));
}
@Test
public void choiceWithLTGT() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new ChoiceParameterDefinition("choice", "Choice 1\nChoice <2>", "choice description"));
project.addProperty(pdp);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
HtmlOption opt = (HtmlOption)DomNodeUtil.selectSingleNode(element, "td/div/select/option[@value='Choice <2>']");
assertNotNull(opt);
assertEquals("Choice <2>", opt.asText());
opt.setSelected(true);
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertNotNull(builder.getEnvVars());
assertEquals("Choice <2>", builder.getEnvVars().get("CHOICE"));
}
@Test
public void sensitiveParameters() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new PasswordParameterDefinition("password", "12345", "password description"));
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertTrue(sensitiveVars.contains("password"));
}
@Test
public void nonSensitiveParameters() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"));
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertFalse(sensitiveVars.contains("string"));
}
@Test
public void mixedSensitivity() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"),
new PasswordParameterDefinition("password", "12345", "password description"),
new StringParameterDefinition("string2", "Value2", "string description")
);
project.addProperty(pdb);
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder);
FreeStyleBuild build = project.scheduleBuild2(0).get();
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
assertNotNull(sensitiveVars);
assertFalse(sensitiveVars.contains("string"));
assertTrue(sensitiveVars.contains("password"));
assertFalse(sensitiveVars.contains("string2"));
}
@Test
@Issue("JENKINS-3539")
public void fileParameterNotSet() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(
new FileParameterDefinition("filename", "description"));
project.addProperty(pdp);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters");
j.submit(form);
Queue.Item q = j.jenkins.getQueue().getItem(project);
if (q != null) q.getFuture().get();
else Thread.sleep(1000);
assertFalse("file must not exist", project.getSomeWorkspace().child("filename").exists());
}
@Test
@Issue("JENKINS-11543")
public void unicodeParametersArePresetCorrectly() throws Exception {
final FreeStyleProject p = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("sname:a¶‱ﻷ", "svalue:a¶‱ﻷ", "sdesc:a¶‱ﻷ"),
new FileParameterDefinition("fname:a¶‱ﻷ", "fdesc:a¶‱ﻷ")
);
p.addProperty(pdb);
WebClient wc = j.createWebClient();
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); // Ignore 405
HtmlPage page = wc.getPage(p, "build");
// java.lang.IllegalArgumentException: No such parameter definition: <gibberish>.
wc.getOptions().setThrowExceptionOnFailingStatusCode(true);
final HtmlForm form = page.getFormByName("parameters");
HtmlFormUtil.submit(form, HtmlFormUtil.getButtonByCaption(form, "Build"));
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_3049_17 |
crossvul-java_data_good_3893_0 | /**
*
*/
package com.salesmanager.shop.store.controller.shoppingCart.facade;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.services.catalog.product.PricingService;
import com.salesmanager.core.business.services.catalog.product.ProductService;
import com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService;
import com.salesmanager.core.business.services.shoppingcart.ShoppingCartCalculationService;
import com.salesmanager.core.business.services.shoppingcart.ShoppingCartService;
import com.salesmanager.core.business.utils.ProductPriceUtils;
import com.salesmanager.core.model.catalog.product.Product;
import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute;
import com.salesmanager.core.model.catalog.product.availability.ProductAvailability;
import com.salesmanager.core.model.catalog.product.price.FinalPrice;
import com.salesmanager.core.model.customer.Customer;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.core.model.shoppingcart.ShoppingCart;
import com.salesmanager.shop.constants.Constants;
import com.salesmanager.shop.model.shoppingcart.CartModificationException;
import com.salesmanager.shop.model.shoppingcart.PersistableShoppingCartItem;
import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartAttribute;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartData;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartItem;
import com.salesmanager.shop.populator.shoppingCart.ReadableShoppingCartPopulator;
import com.salesmanager.shop.populator.shoppingCart.ShoppingCartDataPopulator;
import com.salesmanager.shop.store.api.exception.ResourceNotFoundException;
import com.salesmanager.shop.utils.DateUtil;
import com.salesmanager.shop.utils.ImageFilePath;
/**
* @author Umesh Awasthi
* @version 1.0
* @since 1.0
*/
@Service( value = "shoppingCartFacade" )
public class ShoppingCartFacadeImpl
implements ShoppingCartFacade
{
private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartFacadeImpl.class);
@Inject
private ShoppingCartService shoppingCartService;
@Inject
ShoppingCartCalculationService shoppingCartCalculationService;
@Inject
private ProductPriceUtils productPriceUtils;
@Inject
private ProductService productService;
@Inject
private PricingService pricingService;
@Inject
private ProductAttributeService productAttributeService;
@Inject
@Qualifier("img")
private ImageFilePath imageUtils;
public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception {
ShoppingCart cart = shoppingCartService.getById(id, store);
if(cart!=null) {
shoppingCartService.deleteCart(cart);
}
}
@Override
public void deleteShoppingCart(final String code, final MerchantStore store) throws Exception {
ShoppingCart cart = shoppingCartService.getByCode(code, store);
if(cart!=null) {
shoppingCartService.deleteCart(cart);
}
}
@Override
public ShoppingCartData addItemsToShoppingCart( final ShoppingCartData shoppingCartData,
final ShoppingCartItem item, final MerchantStore store, final Language language,final Customer customer )
throws Exception
{
ShoppingCart cartModel = null;
if(item.getQuantity() < 1) item.setQuantity(1);
/**
* Sometimes a user logs in and a shopping cart is present in db (shoppingCartData
* but ui has no cookie with shopping cart code so the cart code will have
* to be added to the item in order to process add to cart normally
*/
if(shoppingCartData != null && StringUtils.isBlank(item.getCode())) {
item.setCode(shoppingCartData.getCode());
}
if ( !StringUtils.isBlank( item.getCode() ) )
{
// get it from the db
cartModel = getShoppingCartModel( item.getCode(), store );
if ( cartModel == null )
{
cartModel = createCartModel( shoppingCartData.getCode(), store,customer );
}
}
if ( cartModel == null )
{
final String shoppingCartCode =
StringUtils.isNotBlank( shoppingCartData.getCode() ) ? shoppingCartData.getCode() : null;
cartModel = createCartModel( shoppingCartCode, store,customer );
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem =
createCartItem( cartModel, item, store );
boolean duplicateFound = false;
if(CollectionUtils.isEmpty(item.getShoppingCartAttributes())) {//increment quantity
//get duplicate item from the cart
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartModelItems = cartModel.getLineItems();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) {
if(cartItem.getProduct().getId().longValue()==shoppingCartItem.getProduct().getId().longValue()) {
if(CollectionUtils.isEmpty(cartItem.getAttributes())) {
if(!duplicateFound) {
if(!shoppingCartItem.isProductVirtual()) {
cartItem.setQuantity(cartItem.getQuantity() + shoppingCartItem.getQuantity());
}
duplicateFound = true;
break;
}
}
}
}
}
if(!duplicateFound) {
//shoppingCartItem.getAttributes().stream().forEach(a -> {a.setProductAttributeId(productAttributeId);});
cartModel.getLineItems().add( shoppingCartItem );
}
/** Update cart in database with line items **/
shoppingCartService.saveOrUpdate( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
shoppingCartCalculationService.calculate( cartModel, store, language );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem( final ShoppingCart cartModel,
final ShoppingCartItem shoppingCartItem,
final MerchantStore store )
throws Exception
{
Product product = productService.getById( shoppingCartItem.getProductId() );
if ( product == null )
{
throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not exist" );
}
if ( product.getMerchantStore().getId().intValue() != store.getId().intValue() )
{
throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not belong to merchant "
+ store.getId() );
}
/**
* Check if product quantity is 0
* Check if product is available
* Check if date available <= now
*/
Set<ProductAvailability> availabilities = product.getAvailabilities();
if(availabilities == null) {
throw new Exception( "Item with id " + product.getId() + " is not properly configured" );
}
for(ProductAvailability availability : availabilities) {
if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() <= 0) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
}
if(!product.isAvailable()) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem item =
shoppingCartService.populateShoppingCartItem( product );
item.setQuantity( shoppingCartItem.getQuantity() );
item.setShoppingCart( cartModel );
// attributes
List<ShoppingCartAttribute> cartAttributes = shoppingCartItem.getShoppingCartAttributes();
if ( !CollectionUtils.isEmpty( cartAttributes ) )
{
for ( ShoppingCartAttribute attribute : cartAttributes )
{
ProductAttribute productAttribute = productAttributeService.getById( attribute.getAttributeId() );
if ( productAttribute != null
&& productAttribute.getProduct().getId().longValue() == product.getId().longValue() )
{
com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem =
new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( item,
productAttribute );
item.addAttributes( attributeItem );
}
}
}
return item;
}
//used for api
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(ShoppingCart cartModel,
PersistableShoppingCartItem shoppingCartItem, MerchantStore store) throws Exception {
Product product = productService.getById(shoppingCartItem.getProduct());
if (product == null) {
throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not exist");
}
if (product.getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not belong to merchant "
+ store.getId());
}
/**
* Check if product quantity is 0
* Check if product is available
* Check if date available <= now
*/
Set<ProductAvailability> availabilities = product.getAvailabilities();
if(availabilities == null) {
throw new Exception( "Item with id " + product.getId() + " is not properly configured" );
}
for(ProductAvailability availability : availabilities) {
if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() <= 0) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
}
if(!product.isAvailable()) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) {
throw new Exception( "Item with id " + product.getId() + " is not available");
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService
.populateShoppingCartItem(product);
item.setQuantity(shoppingCartItem.getQuantity());
item.setShoppingCart(cartModel);
//set attributes
List<com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute> attributes = shoppingCartItem.getAttributes();
if (!CollectionUtils.isEmpty(attributes)) {
for(com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) {
ProductAttribute productAttribute = productAttributeService.getById(attribute.getId());
if (productAttribute != null
&& productAttribute.getProduct().getId().longValue() == product.getId().longValue()) {
com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem(
item, productAttribute);
item.addAttributes(attributeItem);
}
}
}
return item;
}
@Override
public ShoppingCart createCartModel( final String shoppingCartCode, final MerchantStore store,final Customer customer )
throws Exception
{
final Long CustomerId = customer != null ? customer.getId() : null;
ShoppingCart cartModel = new ShoppingCart();
if ( StringUtils.isNotBlank( shoppingCartCode ) )
{
cartModel.setShoppingCartCode( shoppingCartCode );
}
else
{
cartModel.setShoppingCartCode( uniqueShoppingCartCode() );
}
cartModel.setMerchantStore( store );
if ( CustomerId != null )
{
cartModel.setCustomerId( CustomerId );
}
shoppingCartService.create( cartModel );
return cartModel;
}
private com.salesmanager.core.model.shoppingcart.ShoppingCartItem getEntryToUpdate( final long entryId,
final ShoppingCart cartModel )
{
if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) )
{
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() )
{
if ( shoppingCartItem.getId().longValue() == entryId )
{
LOG.info( "Found line item for given entry id: " + entryId );
return shoppingCartItem;
}
}
}
LOG.info( "Unable to find any entry for given Id: " + entryId );
return null;
}
private Object getKeyValue( final String key )
{
ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return reqAttr.getRequest().getAttribute( key );
}
@Override
public ShoppingCartData getShoppingCartData( final Customer customer, final MerchantStore store,
final String shoppingCartId, Language language)
throws Exception
{
ShoppingCart cart = null;
try
{
if ( customer != null )
{
LOG.info( "Reteriving customer shopping cart..." );
cart = shoppingCartService.getShoppingCart( customer );
}
else
{
if ( StringUtils.isNotBlank( shoppingCartId ) && cart == null )
{
cart = shoppingCartService.getByCode( shoppingCartId, store );
}
}
}
catch ( ServiceException ex )
{
LOG.error( "Error while retriving cart from customer", ex );
}
catch( NoResultException nre) {
//nothing
}
if ( cart == null )
{
return null;
}
LOG.info( "Cart model found." );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
//Language language = (Language) getKeyValue( Constants.LANGUAGE );
MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE );
ShoppingCartData shoppingCartData = shoppingCartDataPopulator.populate( cart, merchantStore, language );
/* List<ShoppingCartItem> unavailables = new ArrayList<ShoppingCartItem>();
List<ShoppingCartItem> availables = new ArrayList<ShoppingCartItem>();
//Take out items no more available
List<ShoppingCartItem> items = shoppingCartData.getShoppingCartItems();
for(ShoppingCartItem item : items) {
String code = item.getProductCode();
Product p =productService.getByCode(code, language);
if(!p.isAvailable()) {
unavailables.add(item);
} else {
availables.add(item);
}
}
shoppingCartData.setShoppingCartItems(availables);
shoppingCartData.setUnavailables(unavailables);*/
return shoppingCartData;
}
//@Override
public ShoppingCartData getShoppingCartData( final ShoppingCart shoppingCartModel, Language language)
throws Exception
{
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
//Language language = (Language) getKeyValue( Constants.LANGUAGE );
MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE );
return shoppingCartDataPopulator.populate( shoppingCartModel, merchantStore, language );
}
@Override
public ShoppingCartData removeCartItem( final Long itemID, final String cartId ,final MerchantStore store,final Language language )
throws Exception
{
if ( StringUtils.isNotBlank( cartId ) )
{
ShoppingCart cartModel = getCartModel( cartId,store );
if ( cartModel != null )
{
if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) )
{
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> shoppingCartItemSet =
new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() )
{
if(shoppingCartItem.getId().longValue() == itemID.longValue() )
{
shoppingCartService.deleteShoppingCartItem(itemID);
} else {
shoppingCartItemSet.add(shoppingCartItem);
}
}
cartModel.setLineItems(shoppingCartItemSet);
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
}
}
return null;
}
@Override
public ShoppingCartData updateCartItem( final Long itemID, final String cartId, final long newQuantity,final MerchantStore store, final Language language )
throws Exception
{
if ( newQuantity < 1 )
{
throw new CartModificationException( "Quantity must not be less than one" );
}
if ( StringUtils.isNotBlank( cartId ) )
{
ShoppingCart cartModel = getCartModel( cartId,store );
if ( cartModel != null )
{
com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate =
getEntryToUpdate( itemID.longValue(), cartModel );
if ( entryToUpdate == null )
{
throw new CartModificationException( "Unknown entry number." );
}
entryToUpdate.getProduct();
LOG.info( "Updating cart entry quantity to" + newQuantity );
entryToUpdate.setQuantity( (int) newQuantity );
List<ProductAttribute> productAttributes = new ArrayList<ProductAttribute>();
productAttributes.addAll( entryToUpdate.getProduct().getAttributes() );
final FinalPrice finalPrice =
productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes );
entryToUpdate.setItemPrice( finalPrice.getFinalPrice() );
shoppingCartService.saveOrUpdate( cartModel );
LOG.info( "Cart entry updated with desired quantity" );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
}
return null;
}
@Override
public ShoppingCartData updateCartItems( final List<ShoppingCartItem> shoppingCartItems, final MerchantStore store, final Language language )
throws Exception
{
Validate.notEmpty(shoppingCartItems,"shoppingCartItems null or empty");
ShoppingCart cartModel = null;
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for(ShoppingCartItem item : shoppingCartItems) {
if(item.getQuantity()<1) {
throw new CartModificationException( "Quantity must not be less than one" );
}
if(cartModel==null) {
cartModel = getCartModel( item.getCode(), store );
}
com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate =
getEntryToUpdate( item.getId(), cartModel );
if ( entryToUpdate == null ) {
throw new CartModificationException( "Unknown entry number." );
}
entryToUpdate.getProduct();
LOG.info( "Updating cart entry quantity to" + item.getQuantity() );
entryToUpdate.setQuantity( (int) item.getQuantity() );
List<ProductAttribute> productAttributes = new ArrayList<ProductAttribute>();
productAttributes.addAll( entryToUpdate.getProduct().getAttributes() );
final FinalPrice finalPrice =
productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes );
entryToUpdate.setItemPrice( finalPrice.getFinalPrice() );
cartItems.add(entryToUpdate);
}
cartModel.setLineItems(cartItems);
shoppingCartService.saveOrUpdate( cartModel );
LOG.info( "Cart entry updated with desired quantity" );
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
shoppingCartDataPopulator.setimageUtils(imageUtils);
return shoppingCartDataPopulator.populate( cartModel, store, language );
}
private ShoppingCart getCartModel( final String cartId,final MerchantStore store )
{
if ( StringUtils.isNotBlank( cartId ) )
{
try
{
return shoppingCartService.getByCode( cartId, store );
}
catch ( ServiceException e )
{
LOG.error( "unable to find any cart asscoiated with this Id: " + cartId );
LOG.error( "error while fetching cart model...", e );
return null;
}
catch( NoResultException nre) {
//nothing
}
}
return null;
}
@Override
public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language language) {
try {
ShoppingCart cartModel = shoppingCartService.getByCode( code, store );
if(cartModel!=null) {
ShoppingCartData cart = getShoppingCartData(cartModel, language);
return cart;
}
} catch( NoResultException nre) {
//nothing
} catch(Exception e) {
LOG.error("Cannot retrieve cart code " + code,e);
}
return null;
}
@Override
public ShoppingCart getShoppingCartModel(String shoppingCartCode,
MerchantStore store) throws Exception {
return shoppingCartService.getByCode( shoppingCartCode, store );
}
@Override
public ShoppingCart getShoppingCartModel(Customer customer,
MerchantStore store) throws Exception {
return shoppingCartService.getByCustomer(customer);
}
@Override
public void saveOrUpdateShoppingCart(ShoppingCart cart) throws Exception {
shoppingCartService.saveOrUpdate(cart);
}
@Override
public ReadableShoppingCart getCart(Customer customer, MerchantStore store, Language language) throws Exception {
Validate.notNull(customer,"Customer cannot be null");
Validate.notNull(customer.getId(),"Customer.id cannot be null or empty");
//Check if customer has an existing shopping cart
ShoppingCart cartModel = shoppingCartService.getByCustomer(customer);
if(cartModel == null) {
return null;
}
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
@Override
public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(item,"PersistableShoppingCartItem cannot be null");
//if cart does not exist create a new one
ShoppingCart cartModel = new ShoppingCart();
cartModel.setMerchantStore(store);
cartModel.setShoppingCartCode(uniqueShoppingCartCode());
return readableShoppingCart(cartModel,item,store,language);
}
@Override
public void removeShoppingCartItem(String cartCode, Long productId,
MerchantStore merchant, Language language) throws Exception {
Validate.notNull(cartCode, "Shopping cart code must not be null");
Validate.notNull(productId, "product id must not be null");
Validate.notNull(merchant, "MerchantStore must not be null");
//get cart
ShoppingCart cart = getCartModel(cartCode, merchant);
if(cart == null) {
throw new ResourceNotFoundException("Cart code [ " + cartCode + " ] not found");
}
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemToDelete = null;
for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cart.getLineItems() )
{
if ( shoppingCartItem.getProduct().getId().longValue() == productId.longValue() )
{
//get cart item
itemToDelete =
getEntryToUpdate( shoppingCartItem.getId(), cart );
//break;
} else {
items.add(shoppingCartItem);
}
}
//delete item
if(itemToDelete!=null) {
shoppingCartService.deleteShoppingCartItem(itemToDelete.getId());
}
//remaining items
if(items.size()>0) {
cart.setLineItems(items);
} else {
cart.getLineItems().clear();
}
//if(items.size()>0) {
shoppingCartService.saveOrUpdate(cart);//update cart with remaining items
//ReadableShoppingCart readableShoppingCart = this.getByCode(cartCode, merchant, language);
//}
}
private ReadableShoppingCart readableShoppingCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store);
//need to check if the item is already in the cart
boolean duplicateFound = false;
//only if item has no attributes
if(CollectionUtils.isEmpty(item.getAttributes())) {//increment quantity
//get duplicate item from the cart
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartModelItems = cartModel.getLineItems();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) {
if(cartItem.getProduct().getId().longValue()==item.getProduct().longValue()) {
if(CollectionUtils.isEmpty(cartItem.getAttributes())) {
if(!duplicateFound) {
if(!itemModel.isProductVirtual()) {
cartItem.setQuantity(cartItem.getQuantity() + item.getQuantity());
}
duplicateFound = true;
break;
}
}
}
}
}
if(!duplicateFound) {
cartModel.getLineItems().add( itemModel );
}
saveShoppingCart( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
private ReadableShoppingCart modifyCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store);
boolean itemModified = false;
//check if existing product
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cartModel.getLineItems();
//com.salesmanager.core.model.shoppingcart.ShoppingCartItem affectedItem = null;
if(!CollectionUtils.isEmpty(items)) {
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> newItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> removeItems = new HashSet<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem anItem : items) {//take care of existing product
if(itemModel.getProduct().getId().longValue() == anItem.getProduct().getId()) {
if(item.getQuantity()==0) {//left aside item to be removed
//don't add it to new list of item
removeItems.add(anItem);
} else {
//new quantity
anItem.setQuantity(item.getQuantity());
newItems.add(anItem);
}
itemModified = true;
} else {
newItems.add(anItem);
}
}
if(!removeItems.isEmpty()) {
for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem emptyItem : removeItems) {
shoppingCartService.deleteShoppingCartItem(emptyItem.getId());
}
}
if(!itemModified) {
newItems.add(itemModel);
}
if(newItems.isEmpty()) {
newItems = null;
}
cartModel.setLineItems(newItems);
} else {
//new item
if(item.getQuantity() > 0) {
cartModel.getLineItems().add( itemModel );
}
}
//if cart items are null just return cart with no items
saveShoppingCart( cartModel );
//refresh cart
cartModel = shoppingCartService.getById(cartModel.getId(), store);
if(cartModel==null) {
return null;
}
shoppingCartCalculationService.calculate( cartModel, store, language );
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
ReadableShoppingCart readableCart = new ReadableShoppingCart();
readableShoppingCart.populate(cartModel, readableCart, store, language);
return readableCart;
}
@Override
public ReadableShoppingCart addToCart(Customer customer, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(customer,"Customer cannot be null");
Validate.notNull(customer.getId(),"Customer.id cannot be null or empty");
if(item.getQuantity() < 1) item.setQuantity(1);
//Check if customer has an existing shopping cart
ShoppingCart cartModel = shoppingCartService.getByCustomer(customer);
//if cart does not exist create a new one
if(cartModel==null) {
cartModel = new ShoppingCart();
cartModel.setCustomerId(customer.getId());
cartModel.setMerchantStore(store);
cartModel.setShoppingCartCode(uniqueShoppingCartCode());
}
return readableShoppingCart(cartModel,item,store,language);
}
@Override
public ReadableShoppingCart modifyCart(String cartCode, PersistableShoppingCartItem item, MerchantStore store,
Language language) throws Exception {
Validate.notNull(cartCode,"PString cart code cannot be null");
Validate.notNull(item,"PersistableShoppingCartItem cannot be null");
ShoppingCart cartModel = this.getCartModel(cartCode, store);
return modifyCart(cartModel,item, store, language);
}
private void saveShoppingCart(ShoppingCart shoppingCart) throws Exception {
shoppingCartService.save(shoppingCart);
}
private String uniqueShoppingCartCode() {
return UUID.randomUUID().toString().replaceAll( "-", "" );
}
@Override
public ReadableShoppingCart getById(Long shoppingCartId, MerchantStore store, Language language) throws Exception {
ShoppingCart cart = shoppingCartService.getById(shoppingCartId);
ReadableShoppingCart readableCart = null;
if(cart != null) {
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
readableShoppingCart.populate(cart, readableCart, store, language);
}
return readableCart;
}
@Override
public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Exception {
return shoppingCartService.getById(id);
}
@Override
public ReadableShoppingCart getByCode(String code, MerchantStore store, Language language) throws Exception {
ShoppingCart cart = shoppingCartService.getByCode(code, store);
ReadableShoppingCart readableCart = null;
if(cart != null) {
ReadableShoppingCartPopulator readableShoppingCart = new ReadableShoppingCartPopulator();
readableShoppingCart.setImageUtils(imageUtils);
readableShoppingCart.setPricingService(pricingService);
readableShoppingCart.setProductAttributeService(productAttributeService);
readableShoppingCart.setShoppingCartCalculationService(shoppingCartCalculationService);
readableCart = readableShoppingCart.populate(cart, null, store, language);
}
return readableCart;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_3893_0 |
crossvul-java_data_bad_2083_0 | /*
* Copyright 2002-2013 the original author or authors.
*
* 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 org.springframework.web.servlet.tags.form;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.Conventions;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.springframework.web.util.HtmlUtils;
/**
* Databinding-aware JSP tag for rendering an HTML '{@code form}' whose
* inner elements are bound to properties on a <em>form object</em>.
*
* <p>Users should place the form object into the
* {@link org.springframework.web.servlet.ModelAndView ModelAndView} when
* populating the data for their view. The name of this form object can be
* configured using the {@link #setModelAttribute "modelAttribute"} property.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Scott Andrews
* @author Rossen Stoyanchev
* @since 2.0
*/
@SuppressWarnings("serial")
public class FormTag extends AbstractHtmlElementTag {
/** The default HTTP method using which form values are sent to the server: "post" */
private static final String DEFAULT_METHOD = "post";
/** The default attribute name: "command" */
public static final String DEFAULT_COMMAND_NAME = "command";
/** The name of the '{@code modelAttribute}' setting */
private static final String MODEL_ATTRIBUTE = "modelAttribute";
/**
* The name of the {@link javax.servlet.jsp.PageContext} attribute under which the
* form object name is exposed.
*/
public static final String MODEL_ATTRIBUTE_VARIABLE_NAME =
Conventions.getQualifiedAttributeName(AbstractFormTag.class, MODEL_ATTRIBUTE);
/** Default method parameter, i.e. {@code _method}. */
private static final String DEFAULT_METHOD_PARAM = "_method";
private static final String FORM_TAG = "form";
private static final String INPUT_TAG = "input";
private static final String ACTION_ATTRIBUTE = "action";
private static final String METHOD_ATTRIBUTE = "method";
private static final String TARGET_ATTRIBUTE = "target";
private static final String ENCTYPE_ATTRIBUTE = "enctype";
private static final String ACCEPT_CHARSET_ATTRIBUTE = "accept-charset";
private static final String ONSUBMIT_ATTRIBUTE = "onsubmit";
private static final String ONRESET_ATTRIBUTE = "onreset";
private static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
private static final String NAME_ATTRIBUTE = "name";
private static final String VALUE_ATTRIBUTE = "value";
private static final String TYPE_ATTRIBUTE = "type";
private TagWriter tagWriter;
private String modelAttribute = DEFAULT_COMMAND_NAME;
private String name;
private String action;
private String servletRelativeAction;
private String method = DEFAULT_METHOD;
private String target;
private String enctype;
private String acceptCharset;
private String onsubmit;
private String onreset;
private String autocomplete;
private String methodParam = DEFAULT_METHOD_PARAM;
/** Caching a previous nested path, so that it may be reset */
private String previousNestedPath;
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
*/
public void setModelAttribute(String modelAttribute) {
this.modelAttribute = modelAttribute;
}
/**
* Get the name of the form attribute in the model.
*/
protected String getModelAttribute() {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* @see #setModelAttribute
*/
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* @see #getModelAttribute
*/
protected String getCommandName() {
return this.modelAttribute;
}
/**
* Set the value of the '{@code name}' attribute.
* <p>May be a runtime expression.
* <p>Name is not a valid attribute for form on XHTML 1.0. However,
* it is sometimes needed for backward compatibility.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the value of the '{@code name}' attribute.
*/
@Override
protected String getName() throws JspException {
return this.name;
}
/**
* Set the value of the '{@code action}' attribute.
* <p>May be a runtime expression.
*/
public void setAction(String action) {
this.action = (action != null ? action : "");
}
/**
* Get the value of the '{@code action}' attribute.
*/
protected String getAction() {
return this.action;
}
/**
* Set the value of the '{@code action}' attribute.
* <p>May be a runtime expression.
*/
public void setServletRelativeAction(String servletRelativeaction) {
this.servletRelativeAction = (servletRelativeaction != null ? servletRelativeaction : "");
}
/**
* Get the value of the '{@code action}' attribute.
*/
protected String getServletRelativeAction() {
return this.servletRelativeAction;
}
/**
* Set the value of the '{@code method}' attribute.
* <p>May be a runtime expression.
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Get the value of the '{@code method}' attribute.
*/
protected String getMethod() {
return this.method;
}
/**
* Set the value of the '{@code target}' attribute.
* <p>May be a runtime expression.
*/
public void setTarget(String target) {
this.target = target;
}
/**
* Get the value of the '{@code target}' attribute.
*/
public String getTarget() {
return this.target;
}
/**
* Set the value of the '{@code enctype}' attribute.
* <p>May be a runtime expression.
*/
public void setEnctype(String enctype) {
this.enctype = enctype;
}
/**
* Get the value of the '{@code enctype}' attribute.
*/
protected String getEnctype() {
return this.enctype;
}
/**
* Set the value of the '{@code acceptCharset}' attribute.
* <p>May be a runtime expression.
*/
public void setAcceptCharset(String acceptCharset) {
this.acceptCharset = acceptCharset;
}
/**
* Get the value of the '{@code acceptCharset}' attribute.
*/
protected String getAcceptCharset() {
return this.acceptCharset;
}
/**
* Set the value of the '{@code onsubmit}' attribute.
* <p>May be a runtime expression.
*/
public void setOnsubmit(String onsubmit) {
this.onsubmit = onsubmit;
}
/**
* Get the value of the '{@code onsubmit}' attribute.
*/
protected String getOnsubmit() {
return this.onsubmit;
}
/**
* Set the value of the '{@code onreset}' attribute.
* <p>May be a runtime expression.
*/
public void setOnreset(String onreset) {
this.onreset = onreset;
}
/**
* Get the value of the '{@code onreset}' attribute.
*/
protected String getOnreset() {
return this.onreset;
}
/**
* Set the value of the '{@code autocomplete}' attribute.
* May be a runtime expression.
*/
public void setAutocomplete(String autocomplete) {
this.autocomplete = autocomplete;
}
/**
* Get the value of the '{@code autocomplete}' attribute.
*/
protected String getAutocomplete() {
return this.autocomplete;
}
/**
* Set the name of the request param for non-browser supported HTTP methods.
*/
public void setMethodParam(String methodParam) {
this.methodParam = methodParam;
}
/**
* Get the name of the request param for non-browser supported HTTP methods.
*/
protected String getMethodParameter() {
return this.methodParam;
}
/**
* Determine if the HTTP method is supported by browsers (i.e. GET or POST).
*/
protected boolean isMethodBrowserSupported(String method) {
return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method));
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParameter();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
private String getHttpMethod() {
return isMethodBrowserSupported(getMethod()) ? getMethod() : DEFAULT_METHOD;
}
private void assertHttpMethod(String method) {
for (HttpMethod httpMethod : HttpMethod.values()) {
if (httpMethod.name().equalsIgnoreCase(method)) {
return;
}
}
throw new IllegalArgumentException("Invalid HTTP method: " + method);
}
/**
* Autogenerated IDs correspond to the form object name.
*/
@Override
protected String autogenerateId() throws JspException {
return resolveModelAttribute();
}
/**
* {@link #evaluate Resolves} and returns the name of the form object.
* @throws IllegalArgumentException if the form object resolves to {@code null}
*/
protected String resolveModelAttribute() throws JspException {
Object resolvedModelAttribute = evaluate(MODEL_ATTRIBUTE, getModelAttribute());
if (resolvedModelAttribute == null) {
throw new IllegalArgumentException(MODEL_ATTRIBUTE + " must not be null");
}
return (String) resolvedModelAttribute;
}
/**
* Resolve the value of the '{@code action}' attribute.
* <p>If the user configured an '{@code action}' value then the result of
* evaluating this value is used. If the user configured an
* '{@code servletRelativeAction}' value then the value is prepended
* with the context and servlet paths, and the result is used. Otherwise, the
* {@link org.springframework.web.servlet.support.RequestContext#getRequestUri()
* originating URI} is used.
*
* @return the value that is to be used for the '{@code action}' attribute
*/
protected String resolveAction() throws JspException {
String action = getAction();
String servletRelativeAction = getServletRelativeAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else if (StringUtils.hasText(servletRelativeAction)) {
String pathToServlet = getRequestContext().getPathToServlet();
if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
servletRelativeAction = pathToServlet + servletRelativeAction;
}
servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
return processAction(servletRelativeAction);
}
else {
String requestUri = getRequestContext().getRequestUri();
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
/**
* Process the action through a {@link RequestDataValueProcessor} instance
* if one is configured or otherwise returns the action unmodified.
*/
private String processAction(String action) {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
action = processor.processAction((HttpServletRequest) request, action, getHttpMethod());
}
return action;
}
/**
* Closes the '{@code form}' block tag and removes the form object name
* from the {@link javax.servlet.jsp.PageContext}.
*/
@Override
public int doEndTag() throws JspException {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
writeHiddenFields(processor.getExtraHiddenFields((HttpServletRequest) request));
}
this.tagWriter.endTag();
return EVAL_PAGE;
}
/**
* Writes the given values as hidden fields.
*/
private void writeHiddenFields(Map<String, String> hiddenFields) throws JspException {
if (hiddenFields != null) {
this.tagWriter.appendValue("<div>\n");
for (String name : hiddenFields.keySet()) {
this.tagWriter.appendValue("<input type=\"hidden\" ");
this.tagWriter.appendValue("name=\"" + name + "\" value=\"" + hiddenFields.get(name) + "\" ");
this.tagWriter.appendValue("/>\n");
}
this.tagWriter.appendValue("</div>");
}
}
/**
* Clears the stored {@link TagWriter}.
*/
@Override
public void doFinally() {
super.doFinally();
this.pageContext.removeAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
if (this.previousNestedPath != null) {
// Expose previous nestedPath value.
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, this.previousNestedPath, PageContext.REQUEST_SCOPE);
}
else {
// Remove exposed nestedPath value.
this.pageContext.removeAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
}
this.tagWriter = null;
this.previousNestedPath = null;
}
/**
* Override resolve CSS class since error class is not supported.
*/
@Override
protected String resolveCssClass() throws JspException {
return ObjectUtils.getDisplayString(evaluate("cssClass", getCssClass()));
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setPath(String path) {
throw new UnsupportedOperationException("The 'path' attribute is not supported for forms");
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setCssErrorClass(String cssErrorClass) {
throw new UnsupportedOperationException("The 'cssErrorClass' attribute is not supported for forms");
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_2083_0 |
crossvul-java_data_bad_883_0 | package ca.uhn.fhir.to;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.client.api.IClientInterceptor;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.client.impl.GenericClient;
import ca.uhn.fhir.to.model.HomeRequest;
import ca.uhn.fhir.util.ExtensionConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.hl7.fhir.dstu3.model.CapabilityStatement;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestComponent;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestResourceComponent;
import org.hl7.fhir.dstu3.model.DecimalType;
import org.hl7.fhir.dstu3.model.Extension;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.TemplateEngine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
public class BaseController {
static final String PARAM_RESOURCE = "resource";
static final String RESOURCE_COUNT_EXT_URL = "http://hl7api.sourceforge.net/hapi-fhir/res/extdefs.html#resourceCount";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseController.class);
@Autowired
protected TesterConfig myConfig;
private Map<FhirVersionEnum, FhirContext> myContexts = new HashMap<FhirVersionEnum, FhirContext>();
private List<String> myFilterHeaders;
@Autowired
private ITemplateEngine myTemplateEngine;
public BaseController() {
super();
}
protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
final String serverId = theRequest.getServerIdWithDefault(myConfig);
final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
final String serverName = theRequest.getServerName(myConfig);
final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
theModel.put("serverId", serverId);
theModel.put("base", serverBase);
theModel.put("baseName", serverName);
theModel.put("apiKey", apiKey);
theModel.put("resourceName", defaultString(theRequest.getResource()));
theModel.put("encoding", theRequest.getEncoding());
theModel.put("pretty", theRequest.getPretty());
theModel.put("_summary", theRequest.get_summary());
theModel.put("serverEntries", myConfig.getIdToServerName());
return loadAndAddConf(theServletRequest, theRequest, theModel);
}
private Header[] applyHeaderFilters(Header[] theAllHeaders) {
if (myFilterHeaders == null || myFilterHeaders.isEmpty()) {
return theAllHeaders;
}
ArrayList<Header> retVal = new ArrayList<Header>();
for (Header next : theAllHeaders) {
if (!myFilterHeaders.contains(next.getName().toLowerCase())) {
retVal.add(next);
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private Header[] applyHeaderFilters(Map<String, List<String>> theAllHeaders) {
ArrayList<Header> retVal = new ArrayList<Header>();
for (String nextKey : theAllHeaders.keySet()) {
for (String nextValue : theAllHeaders.get(nextKey)) {
if (myFilterHeaders == null || !myFilterHeaders.contains(nextKey.toLowerCase())) {
retVal.add(new BasicHeader(nextKey, nextValue));
}
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private String format(String theResultBody, EncodingEnum theEncodingEnum) {
String str = StringEscapeUtils.escapeHtml4(theResultBody);
if (str == null || theEncodingEnum == null) {
return str;
}
StringBuilder b = new StringBuilder();
if (theEncodingEnum == EncodingEnum.JSON) {
boolean inValue = false;
boolean inQuote = false;
for (int i = 0; i < str.length(); i++) {
char prevChar = (i > 0) ? str.charAt(i - 1) : ' ';
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (prevChar != '\\' && nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
} else if (nextChar == '\\' && nextChar2 == '"') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else {
if (nextChar == ':') {
inValue = true;
b.append(nextChar);
} else if (nextChar == '[' || nextChar == '{') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '{' || nextChar == '}' || nextChar == ',') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
if (inValue) {
b.append("<span class='hlQuot'>"");
} else {
b.append("<span class='hlTagName'>"");
}
inQuote = true;
i += 5;
} else if (nextChar == ':') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = true;
} else {
b.append(nextChar);
}
}
}
} else {
boolean inQuote = false;
boolean inTag = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else if (inTag) {
if (nextChar == '&' && nextChar2 == 'g' && nextChar3 == 't' && nextChar4 == ';') {
b.append("</span><span class='hlControl'>></span>");
inTag = false;
i += 3;
} else if (nextChar == ' ') {
b.append("</span><span class='hlAttr'>");
b.append(nextChar);
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("<span class='hlQuot'>"");
inQuote = true;
i += 5;
} else {
b.append(nextChar);
}
} else {
if (nextChar == '&' && nextChar2 == 'l' && nextChar3 == 't' && nextChar4 == ';') {
b.append("<span class='hlControl'><</span><span class='hlTagName'>");
inTag = true;
i += 3;
} else {
b.append(nextChar);
}
}
}
}
return b.toString();
}
private String formatUrl(String theUrlBase, String theResultBody) {
String str = theResultBody;
if (str == null) {
return str;
}
try {
str = URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
ourLog.error("Should not happen", e);
}
StringBuilder b = new StringBuilder();
b.append("<span class='hlUrlBase'>");
boolean inParams = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
// char nextChar2 = i < str.length()-2 ? str.charAt(i+1):' ';
// char nextChar3 = i < str.length()-2 ? str.charAt(i+2):' ';
if (!inParams) {
if (nextChar == '?') {
inParams = true;
b.append("</span><wbr /><span class='hlControl'>?</span><span class='hlTagName'>");
} else {
if (i == theUrlBase.length()) {
b.append("</span><wbr /><span class='hlText'>");
}
b.append(nextChar);
}
} else {
if (nextChar == '&') {
b.append("</span><wbr /><span class='hlControl'>&</span><span class='hlTagName'>");
} else if (nextChar == '=') {
b.append("</span><span class='hlControl'>=</span><span class='hlAttr'>");
// }else if (nextChar=='%' && Character.isLetterOrDigit(nextChar2)&& Character.isLetterOrDigit(nextChar3)) {
// URLDecoder.decode(s, enc)
} else {
b.append(nextChar);
}
}
}
if (inParams) {
b.append("</span>");
}
return b.toString();
}
protected FhirContext getContext(HomeRequest theRequest) {
FhirVersionEnum version = theRequest.getFhirVersion(myConfig);
FhirContext retVal = myContexts.get(version);
if (retVal == null) {
retVal = newContext(version);
myContexts.put(version, retVal);
}
return retVal;
}
protected RuntimeResourceDefinition getResourceType(HomeRequest theRequest, HttpServletRequest theReq) throws ServletException {
String resourceName = StringUtils.defaultString(theReq.getParameter(PARAM_RESOURCE));
RuntimeResourceDefinition def = getContext(theRequest).getResourceDefinition(resourceName);
if (def == null) {
throw new ServletException("Invalid resourceName: " + resourceName);
}
return def;
}
protected ResultType handleClientException(GenericClient theClient, Exception e, ModelMap theModel) {
ResultType returnsResource;
returnsResource = ResultType.NONE;
ourLog.warn("Failed to invoke server", e);
if (e != null) {
theModel.put("errorMsg", toDisplayError("Error: " + e.getMessage(), e));
}
return returnsResource;
}
private IBaseResource loadAndAddConf(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
switch (theRequest.getFhirVersion(myConfig)) {
case DSTU2:
return loadAndAddConfDstu2(theServletRequest, theRequest, theModel);
case DSTU3:
return loadAndAddConfDstu3(theServletRequest, theRequest, theModel);
case R4:
return loadAndAddConfR4(theServletRequest, theRequest, theModel);
case DSTU2_1:
case DSTU2_HL7ORG:
break;
}
throw new IllegalStateException("Unknown version: " + theRequest.getFhirVersion(myConfig));
}
private IResource loadAndAddConfDstu2(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
ca.uhn.fhir.model.dstu2.resource.Conformance conformance;
try {
conformance = (ca.uhn.fhir.model.dstu2.resource.Conformance) client.fetchConformance().ofType(Conformance.class).execute();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement, error was: {}", e.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new ca.uhn.fhir.model.dstu2.resource.Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IBaseResource loadAndAddConfDstu3(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.dstu3.model.CapabilityStatement capabilityStatement = new CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.dstu3.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement, error was: {}", ex.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<CapabilityStatementRestResourceComponent>() {
@Override
public int compare(CapabilityStatementRestResourceComponent theO1, CapabilityStatementRestResourceComponent theO2) {
DecimalType count1 = new DecimalType();
List<Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalType) count1exts.get(0).getValue();
}
DecimalType count2 = new DecimalType();
List<Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
private IBaseResource loadAndAddConfR4(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.r4.model.CapabilityStatement capabilityStatement = new org.hl7.fhir.r4.model.CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.r4.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement, error was: {}", ex.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<org.hl7.fhir.r4.model.Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((org.hl7.fhir.r4.model.DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent>() {
@Override
public int compare(org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent theO1, org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent theO2) {
org.hl7.fhir.r4.model.DecimalType count1 = new org.hl7.fhir.r4.model.DecimalType();
List<org.hl7.fhir.r4.model.Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (org.hl7.fhir.r4.model.DecimalType) count1exts.get(0).getValue();
}
org.hl7.fhir.r4.model.DecimalType count2 = new org.hl7.fhir.r4.model.DecimalType();
List<org.hl7.fhir.r4.model.Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (org.hl7.fhir.r4.model.DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
protected String logPrefix(ModelMap theModel) {
return "[server=" + theModel.get("serverId") + "] - ";
}
protected FhirContext newContext(FhirVersionEnum version) {
FhirContext retVal;
retVal = new FhirContext(version);
return retVal;
}
private String parseNarrative(HomeRequest theRequest, EncodingEnum theCtEnum, String theResultBody) {
try {
IBaseResource par = theCtEnum.newParser(getContext(theRequest)).parseResource(theResultBody);
String retVal;
if (par instanceof IResource) {
IResource resource = (IResource) par;
retVal = resource.getText().getDiv().getValueAsString();
} else if (par instanceof IDomainResource) {
retVal = ((IDomainResource) par).getText().getDivAsString();
} else {
retVal = null;
}
return StringUtils.defaultString(retVal);
} catch (Exception e) {
ourLog.error("Failed to parse resource", e);
return "";
}
}
protected String preProcessMessageBody(String theBody) {
if (theBody == null) {
return "";
}
String retVal = theBody.trim();
StringBuilder b = new StringBuilder();
for (int i = 0; i < retVal.length(); i++) {
char nextChar = retVal.charAt(i);
int nextCharI = nextChar;
if (nextCharI == 65533) {
b.append(' ');
continue;
}
if (nextCharI == 160) {
b.append(' ');
continue;
}
if (nextCharI == 194) {
b.append(' ');
continue;
}
b.append(nextChar);
}
retVal = b.toString();
return retVal;
}
protected void processAndAddLastClientInvocation(GenericClient theClient, ResultType theResultType, ModelMap theModelMap, long theLatency, String outcomeDescription,
CaptureInterceptor theInterceptor, HomeRequest theRequest) {
try {
// ApacheHttpRequest lastRequest = theInterceptor.getLastRequest();
// HttpResponse lastResponse = theInterceptor.getLastResponse();
// String requestBody = null;
// String requestUrl = lastRequest != null ? lastRequest.getApacheRequest().getURI().toASCIIString() : null;
// String action = lastRequest != null ? lastRequest.getApacheRequest().getMethod() : null;
// String resultStatus = lastResponse != null ? lastResponse.getStatusLine().toString() : null;
// String resultBody = StringUtils.defaultString(theInterceptor.getLastResponseBody());
//
// if (lastRequest instanceof HttpEntityEnclosingRequest) {
// HttpEntity entity = ((HttpEntityEnclosingRequest) lastRequest).getEntity();
// if (entity.isRepeatable()) {
// requestBody = IOUtils.toString(entity.getContent());
// }
// }
//
// ContentType ct = lastResponse != null ? ContentType.get(lastResponse.getEntity()) : null;
// String mimeType = ct != null ? ct.getMimeType() : null;
IHttpRequest lastRequest = theInterceptor.getLastRequest();
IHttpResponse lastResponse = theInterceptor.getLastResponse();
String requestBody = null;
String requestUrl = null;
String action = null;
String resultStatus = null;
String resultBody = null;
String mimeType = null;
ContentType ct = null;
if (lastRequest != null) {
requestBody = lastRequest.getRequestBodyFromStream();
requestUrl = lastRequest.getUri();
action = lastRequest.getHttpVerbName();
}
if (lastResponse != null) {
resultStatus = "HTTP " + lastResponse.getStatus() + " " + lastResponse.getStatusInfo();
lastResponse.bufferEntity();
resultBody = IOUtils.toString(lastResponse.readEntity(), Constants.CHARSET_UTF8);
List<String> ctStrings = lastResponse.getHeaders(Constants.HEADER_CONTENT_TYPE);
if (ctStrings != null && ctStrings.isEmpty() == false) {
ct = ContentType.parse(ctStrings.get(0));
mimeType = ct.getMimeType();
}
}
EncodingEnum ctEnum = EncodingEnum.forContentType(mimeType);
String narrativeString = "";
StringBuilder resultDescription = new StringBuilder();
IBaseResource riBundle = null;
FhirContext context = getContext(theRequest);
if (ctEnum == null) {
resultDescription.append("Non-FHIR response");
} else {
switch (ctEnum) {
case JSON:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("JSON resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("JSON bundle");
riBundle = context.newJsonParser().parseResource(resultBody);
}
break;
case XML:
default:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("XML resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("XML bundle");
riBundle = context.newXmlParser().parseResource(resultBody);
}
break;
}
}
resultDescription.append(" (").append(defaultString(resultBody).length() + " bytes)");
Header[] requestHeaders = lastRequest != null ? applyHeaderFilters(lastRequest.getAllHeaders()) : new Header[0];
Header[] responseHeaders = lastResponse != null ? applyHeaderFilters(lastResponse.getAllHeaders()) : new Header[0];
theModelMap.put("outcomeDescription", outcomeDescription);
theModelMap.put("resultDescription", resultDescription.toString());
theModelMap.put("action", action);
theModelMap.put("ri", riBundle instanceof IAnyResource);
theModelMap.put("riBundle", riBundle);
theModelMap.put("resultStatus", resultStatus);
theModelMap.put("requestUrl", requestUrl);
theModelMap.put("requestUrlText", formatUrl(theClient.getUrlBase(), requestUrl));
String requestBodyText = format(requestBody, ctEnum);
theModelMap.put("requestBody", requestBodyText);
String resultBodyText = format(resultBody, ctEnum);
theModelMap.put("resultBody", resultBodyText);
theModelMap.put("resultBodyIsLong", resultBodyText.length() > 1000);
theModelMap.put("requestHeaders", requestHeaders);
theModelMap.put("responseHeaders", responseHeaders);
theModelMap.put("narrative", narrativeString);
theModelMap.put("latencyMs", theLatency);
} catch (Exception e) {
ourLog.error("Failure during processing", e);
theModelMap.put("errorMsg", toDisplayError("Error during processing: " + e.getMessage(), e));
}
}
/**
* A hook to be overridden by subclasses. The overriding method can modify the error message
* based on its content and/or the related exception.
*
* @param theErrorMsg The original error message to be displayed to the user.
* @param theException The exception that occurred. May be null.
* @return The modified error message to be displayed to the user.
*/
protected String toDisplayError(String theErrorMsg, Exception theException) {
return theErrorMsg;
}
protected enum ResultType {
BUNDLE, NONE, RESOURCE, TAGLIST
}
public static class CaptureInterceptor implements IClientInterceptor {
private IHttpRequest myLastRequest;
private IHttpResponse myLastResponse;
// private String myResponseBody;
public IHttpRequest getLastRequest() {
return myLastRequest;
}
public IHttpResponse getLastResponse() {
return myLastResponse;
}
// public String getLastResponseBody() {
// return myResponseBody;
// }
@Override
public void interceptRequest(IHttpRequest theRequest) {
assert myLastRequest == null;
myLastRequest = theRequest;
}
@Override
public void interceptResponse(IHttpResponse theResponse) throws IOException {
assert myLastResponse == null;
myLastResponse = theResponse;
// myLastResponse = ((ApacheHttpResponse) theResponse).getResponse();
//
// HttpEntity respEntity = myLastResponse.getEntity();
// if (respEntity != null) {
// final byte[] bytes;
// try {
// bytes = IOUtils.toByteArray(respEntity.getContent());
// } catch (IllegalStateException e) {
// throw new InternalErrorException(e);
// }
//
// myResponseBody = new String(bytes, "UTF-8");
// myLastResponse.setEntity(new MyEntityWrapper(respEntity, bytes));
// }
}
// private static class MyEntityWrapper extends HttpEntityWrapper {
//
// private byte[] myBytes;
//
// public MyEntityWrapper(HttpEntity theWrappedEntity, byte[] theBytes) {
// super(theWrappedEntity);
// myBytes = theBytes;
// }
//
// @Override
// public InputStream getContent() throws IOException {
// return new ByteArrayInputStream(myBytes);
// }
//
// @Override
// public void writeTo(OutputStream theOutstream) throws IOException {
// theOutstream.write(myBytes);
// }
//
// }
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_883_0 |
crossvul-java_data_good_1165_1 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.lifecycle;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.CLIENT_WINDOW_PARAM;
import java.util.Map;
import javax.faces.component.UINamingContainer;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.ResponseStateManager;
public class ClientWindowImpl extends ClientWindow {
String id;
public ClientWindowImpl() {
}
@Override
public Map<String, String> getQueryURLParameters(FacesContext context) {
return null;
}
@Override
public void decode(FacesContext context) {
Map<String, String> requestParamMap = context.getExternalContext().getRequestParameterMap();
if (isClientWindowRenderModeEnabled(context)) {
id = requestParamMap.get(ResponseStateManager.CLIENT_WINDOW_URL_PARAM);
}
// The hidden field always takes precedence, if present.
String paramName = CLIENT_WINDOW_PARAM.getName(context);
if (requestParamMap.containsKey(paramName)) {
id = requestParamMap.get(paramName);
}
if (null == id) {
id = calculateClientWindow(context);
}
}
private String calculateClientWindow(FacesContext context) {
synchronized(context.getExternalContext().getSession(true)) {
final String clientWindowCounterKey = "com.sun.faces.lifecycle.ClientWindowCounterKey";
ExternalContext extContext = context.getExternalContext();
Map<String, Object> sessionAttrs = extContext.getSessionMap();
Integer counter = (Integer) sessionAttrs.get(clientWindowCounterKey);
if (null == counter) {
counter = Integer.valueOf(0);
}
char sep = UINamingContainer.getSeparatorChar(context);
id = extContext.getSessionId(true) + sep +
+ counter;
sessionAttrs.put(clientWindowCounterKey, ++counter);
}
return id;
}
@Override
public String getId() {
return id;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_1165_1 |
crossvul-java_data_good_24_3 | package org.jolokia.jvmagent.handler;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.management.MalformedObjectNameException;
import javax.management.RuntimeMBeanException;
import javax.security.auth.Subject;
import com.sun.net.httpserver.*;
import org.jolokia.backend.BackendManager;
import org.jolokia.config.ConfigKey;
import org.jolokia.config.Configuration;
import org.jolokia.discovery.AgentDetails;
import org.jolokia.discovery.DiscoveryMulticastResponder;
import org.jolokia.http.HttpRequestHandler;
import org.jolokia.jvmagent.ParsedUri;
import org.jolokia.restrictor.*;
import org.jolokia.util.*;
import org.json.simple.JSONAware;
import org.json.simple.JSONStreamAware;
/**
* HttpHandler for handling a Jolokia request
*
* @author roland
* @since Mar 3, 2010
*/
public class JolokiaHttpHandler implements HttpHandler {
// Backendmanager for doing request
private BackendManager backendManager;
// The HttpRequestHandler
private HttpRequestHandler requestHandler;
// Context of this request
private String context;
// Content type matching
private Pattern contentTypePattern = Pattern.compile(".*;\\s*charset=([^;,]+)\\s*.*");
// Configuration of this handler
private Configuration configuration;
// Loghandler to use
private final LogHandler logHandler;
// Respond for discovery mc requests
private DiscoveryMulticastResponder discoveryMulticastResponder;
/**
* Create a new HttpHandler for processing HTTP request
*
* @param pConfig jolokia specific config tuning the processing behaviour
*/
public JolokiaHttpHandler(Configuration pConfig) {
this(pConfig, null);
}
/**
* Create a new HttpHandler for processing HTTP request
*
* @param pConfig jolokia specific config tuning the processing behaviour
* @param pLogHandler log-handler the log handler to use for jolokia
*/
public JolokiaHttpHandler(Configuration pConfig, LogHandler pLogHandler) {
configuration = pConfig;
context = pConfig.get(ConfigKey.AGENT_CONTEXT);
if (!context.endsWith("/")) {
context += "/";
}
logHandler = pLogHandler != null ? pLogHandler : createLogHandler(pConfig.get(ConfigKey.LOGHANDLER_CLASS), pConfig.get(ConfigKey.DEBUG));
}
/**
* Start the handler
*
* @param pLazy whether initialisation should be done lazy.
*/
public void start(boolean pLazy) {
Restrictor restrictor = createRestrictor();
backendManager = new BackendManager(configuration, logHandler, restrictor, pLazy);
requestHandler = new HttpRequestHandler(configuration, backendManager, logHandler);
if (listenForDiscoveryMcRequests(configuration)) {
try {
discoveryMulticastResponder = new DiscoveryMulticastResponder(backendManager, restrictor, logHandler);
discoveryMulticastResponder.start();
} catch (IOException e) {
logHandler.error("Cannot start discovery multicast handler: " + e, e);
}
}
}
/**
* Hook for creating an own restrictor
*
* @return return restrictor or null if no restrictor is needed.
*/
protected Restrictor createRestrictor() {
return RestrictorFactory.createRestrictor(configuration, logHandler);
}
private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
String enable = pConfig.get(ConfigKey.DISCOVERY_ENABLED);
String url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
return url != null || enable == null || Boolean.valueOf(enable);
}
/**
* Start the handler and remember connection details which are useful for discovery messages
*
* @param pLazy whether initialisation should be done lazy.
* @param pUrl agent URL
* @param pSecured whether the communication is secured or not
*/
public void start(boolean pLazy, String pUrl, boolean pSecured) {
start(pLazy);
AgentDetails details = backendManager.getAgentDetails();
details.setUrl(pUrl);
details.setSecured(pSecured);
}
/**
* Stop the handler
*/
public void stop() {
if (discoveryMulticastResponder != null) {
discoveryMulticastResponder.stop();
discoveryMulticastResponder = null;
}
backendManager.destroy();
backendManager = null;
requestHandler = null;
}
/**
* Handle a request. If the handler is not yet started, an exception is thrown. If running with JAAS
* security enabled it will run as the given subject.
*
* @param pHttpExchange the request/response object
* @throws IOException if something fails during handling
* @throws IllegalStateException if the handler has not yet been started
*/
public void handle(final HttpExchange pHttpExchange) throws IOException {
try {
checkAuthentication(pHttpExchange);
Subject subject = (Subject) pHttpExchange.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE);
if (subject != null) {
doHandleAs(subject, pHttpExchange);
} else {
doHandle(pHttpExchange);
}
} catch (SecurityException exp) {
sendForbidden(pHttpExchange,exp);
}
}
// run as priviledged action
private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) {
try {
Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException {
doHandle(pHttpExchange);
return null;
}
});
} catch (PrivilegedActionException e) {
throw new SecurityException("Security exception: " + e.getCause(),e.getCause());
}
}
/**
* Protocol based authentication checks called very early and before handling a request.
* If the check fails a security exception must be thrown
*
* The default implementation does nothing and should be overridden for a valid check.
*
* @param pHttpExchange exchange to check
* @throws SecurityException if check fails.
*/
protected void checkAuthentication(HttpExchange pHttpExchange) throws SecurityException { }
@SuppressWarnings({"PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause"})
public void doHandle(HttpExchange pExchange) throws IOException {
if (requestHandler == null) {
throw new IllegalStateException("Handler not yet started");
}
JSONAware json = null;
URI uri = pExchange.getRequestURI();
ParsedUri parsedUri = new ParsedUri(uri, context);
try {
// Check access policy
InetSocketAddress address = pExchange.getRemoteAddress();
requestHandler.checkAccess(getHostName(address),
address.getAddress().getHostAddress(),
extractOriginOrReferer(pExchange));
String method = pExchange.getRequestMethod();
// If a callback is given, check this is a valid javascript function name
validateCallbackIfGiven(parsedUri);
// Dispatch for the proper HTTP request method
if ("GET".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executeGetRequest(parsedUri);
} else if ("POST".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executePostRequest(pExchange, parsedUri);
} else if ("OPTIONS".equalsIgnoreCase(method)) {
performCorsPreflightCheck(pExchange);
} else {
throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
}
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
sendResponse(pExchange, parsedUri, json);
}
}
private void validateCallbackIfGiven(ParsedUri pUri) {
String callback = pUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
if (callback != null && !MimeTypeUtil.isValidCallback(callback)) {
throw new IllegalArgumentException("Invalid callback name given, which must be a valid javascript function name");
}
}
// ========================================================================
// Used for checking origin or referer is an origin policy is enabled
private String extractOriginOrReferer(HttpExchange pExchange) {
Headers headers = pExchange.getRequestHeaders();
String origin = headers.getFirst("Origin");
if (origin == null) {
origin = headers.getFirst("Referer");
}
return origin != null ? origin.replaceAll("[\\n\\r]*","") : null;
}
// Return hostnmae of given address, but only when reverse DNS lookups are allowed
private String getHostName(InetSocketAddress address) {
return configuration.getAsBoolean(ConfigKey.ALLOW_DNS_REVERSE_LOOKUP) ? address.getHostName() : null;
}
private JSONAware executeGetRequest(ParsedUri parsedUri) {
return requestHandler.handleGetRequest(parsedUri.getUri().toString(),parsedUri.getPathInfo(), parsedUri.getParameterMap());
}
private JSONAware executePostRequest(HttpExchange pExchange, ParsedUri pUri) throws MalformedObjectNameException, IOException {
String encoding = null;
Headers headers = pExchange.getRequestHeaders();
String cType = headers.getFirst("Content-Type");
if (cType != null) {
Matcher matcher = contentTypePattern.matcher(cType);
if (matcher.matches()) {
encoding = matcher.group(1);
}
}
InputStream is = pExchange.getRequestBody();
return requestHandler.handlePostRequest(pUri.toString(),is, encoding, pUri.getParameterMap());
}
private void performCorsPreflightCheck(HttpExchange pExchange) {
Headers requestHeaders = pExchange.getRequestHeaders();
Map<String,String> respHeaders =
requestHandler.handleCorsPreflightRequest(requestHeaders.getFirst("Origin"),
requestHeaders.getFirst("Access-Control-Request-Headers"));
Headers responseHeaders = pExchange.getResponseHeaders();
for (Map.Entry<String,String> entry : respHeaders.entrySet()) {
responseHeaders.set(entry.getKey(), entry.getValue());
}
}
private void setHeaders(HttpExchange pExchange) {
String origin = requestHandler.extractCorsOrigin(pExchange.getRequestHeaders().getFirst("Origin"));
Headers headers = pExchange.getResponseHeaders();
if (origin != null) {
headers.set("Access-Control-Allow-Origin",origin);
headers.set("Access-Control-Allow-Credentials","true");
}
// Avoid caching at all costs
headers.set("Cache-Control", "no-cache");
headers.set("Pragma","no-cache");
// Check for a date header and set it accordingly to the recommendations of
// RFC-2616. See also {@link AgentServlet#setNoCacheHeaders()}
// Issue: #71
Calendar cal = Calendar.getInstance();
headers.set("Date",formatHeaderDate(cal.getTime()));
// 1h in the past since it seems, that some servlet set the date header on their
// own so that it cannot be guaranteed that these headers are really equals.
// It happened on Tomcat that "Date:" was finally set *before* "Expires:" in the final
// answers sometimes which seems to be an implementation peculiarity from Tomcat
cal.add(Calendar.HOUR, -1);
headers.set("Expires",formatHeaderDate(cal.getTime()));
}
private void sendForbidden(HttpExchange pExchange, SecurityException securityException) throws IOException {
String response = "403 (Forbidden)\n";
if (securityException != null && securityException.getMessage() != null) {
response += "\n" + securityException.getMessage() + "\n";
}
pExchange.sendResponseHeaders(403, response.length());
OutputStream os = pExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private void sendResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
boolean streaming = configuration.getAsBoolean(ConfigKey.STREAMING);
if (streaming) {
JSONStreamAware jsonStream = (JSONStreamAware)pJson;
sendStreamingResponse(pExchange, pParsedUri, jsonStream);
} else {
// Fallback, send as one object
// TODO: Remove for 2.0
sendAllJSON(pExchange, pParsedUri, pJson);
}
}
private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException {
Headers headers = pExchange.getResponseHeaders();
if (pJson != null) {
headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
pExchange.sendResponseHeaders(200, 0);
Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8");
String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
IoUtil.streamResponseAndClose(writer, pJson, callback != null && MimeTypeUtil.isValidCallback(callback) ? callback : null);
} else {
headers.set("Content-Type", "text/plain");
pExchange.sendResponseHeaders(200,-1);
}
}
private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
OutputStream out = null;
try {
Headers headers = pExchange.getResponseHeaders();
if (pJson != null) {
headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
String json = pJson.toJSONString();
String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
String content = callback != null && MimeTypeUtil.isValidCallback(callback) ? callback + "(" + json + ");" : json;
byte[] response = content.getBytes("UTF8");
pExchange.sendResponseHeaders(200,response.length);
out = pExchange.getResponseBody();
out.write(response);
} else {
headers.set("Content-Type", "text/plain");
pExchange.sendResponseHeaders(200,-1);
}
} finally {
if (out != null) {
// Always close in order to finish the request.
// Otherwise the thread blocks.
out.close();
}
}
}
// Get the proper mime type according to configuration
private String getMimeType(ParsedUri pParsedUri) {
return MimeTypeUtil.getResponseMimeType(
pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
configuration.get(ConfigKey.MIME_TYPE),
pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()));
}
// Creat a log handler from either the given class or by creating a default log handler printing
// out to stderr
private LogHandler createLogHandler(String pLogHandlerClass, String pDebug) {
if (pLogHandlerClass != null) {
return ClassUtil.newInstance(pLogHandlerClass);
} else {
final boolean debug = Boolean.valueOf(pDebug);
return new LogHandler.StdoutLogHandler(debug);
}
}
private String formatHeaderDate(Date date) {
DateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
return rfc1123Format.format(date);
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_24_3 |
crossvul-java_data_bad_4992_0 | /**
* Copyright (c) 2013--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.groups;
import com.redhat.rhn.domain.server.ManagedServerGroup;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnAction;
import com.redhat.rhn.frontend.struts.RhnHelper;
import com.redhat.rhn.manager.system.ServerGroupManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* DeleteGroupAction
* @version 1.0
*/
public class DeleteGroupAction extends RhnAction {
private static final String DELETED_MESSAGE_KEY = "systemgroup.delete.deleted";
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
RequestContext context = new RequestContext(request);
ManagedServerGroup serverGroup = context.lookupAndBindServerGroup();
if (context.isSubmitted()) {
String [] params = {serverGroup.getName()};
ServerGroupManager manager = ServerGroupManager.getInstance();
manager.remove(context.getCurrentUser(), serverGroup);
getStrutsDelegate().saveMessage(DELETED_MESSAGE_KEY, params, request);
return mapping.findForward("success");
}
return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_4992_0 |
crossvul-java_data_good_883_0 | package ca.uhn.fhir.to;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.client.api.IClientInterceptor;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.client.impl.GenericClient;
import ca.uhn.fhir.to.model.HomeRequest;
import ca.uhn.fhir.util.ExtensionConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.hl7.fhir.dstu3.model.CapabilityStatement;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestComponent;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestResourceComponent;
import org.hl7.fhir.dstu3.model.DecimalType;
import org.hl7.fhir.dstu3.model.Extension;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.thymeleaf.ITemplateEngine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
public class BaseController {
static final String PARAM_RESOURCE = "resource";
static final String RESOURCE_COUNT_EXT_URL = "http://hl7api.sourceforge.net/hapi-fhir/res/extdefs.html#resourceCount";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseController.class);
@Autowired
protected TesterConfig myConfig;
private Map<FhirVersionEnum, FhirContext> myContexts = new HashMap<FhirVersionEnum, FhirContext>();
private List<String> myFilterHeaders;
@Autowired
private ITemplateEngine myTemplateEngine;
public BaseController() {
super();
}
protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
final String serverId = theRequest.getServerIdWithDefault(myConfig);
final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
final String serverName = theRequest.getServerName(myConfig);
final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
theModel.put("serverId", sanitizeInput(serverId));
theModel.put("base", sanitizeInput(serverBase));
theModel.put("baseName", sanitizeInput(serverName));
theModel.put("apiKey", sanitizeInput(apiKey));
theModel.put("resourceName", sanitizeInput(defaultString(theRequest.getResource())));
theModel.put("encoding", sanitizeInput(theRequest.getEncoding()));
theModel.put("pretty", sanitizeInput(theRequest.getPretty()));
theModel.put("_summary", sanitizeInput(theRequest.get_summary()));
theModel.put("serverEntries", myConfig.getIdToServerName());
return loadAndAddConf(theServletRequest, theRequest, theModel);
}
private Header[] applyHeaderFilters(Header[] theAllHeaders) {
if (myFilterHeaders == null || myFilterHeaders.isEmpty()) {
return theAllHeaders;
}
ArrayList<Header> retVal = new ArrayList<Header>();
for (Header next : theAllHeaders) {
if (!myFilterHeaders.contains(next.getName().toLowerCase())) {
retVal.add(next);
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private Header[] applyHeaderFilters(Map<String, List<String>> theAllHeaders) {
ArrayList<Header> retVal = new ArrayList<Header>();
for (String nextKey : theAllHeaders.keySet()) {
for (String nextValue : theAllHeaders.get(nextKey)) {
if (myFilterHeaders == null || !myFilterHeaders.contains(nextKey.toLowerCase())) {
retVal.add(new BasicHeader(nextKey, nextValue));
}
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private String format(String theResultBody, EncodingEnum theEncodingEnum) {
String str = StringEscapeUtils.escapeHtml4(theResultBody);
if (str == null || theEncodingEnum == null) {
return str;
}
StringBuilder b = new StringBuilder();
if (theEncodingEnum == EncodingEnum.JSON) {
boolean inValue = false;
boolean inQuote = false;
for (int i = 0; i < str.length(); i++) {
char prevChar = (i > 0) ? str.charAt(i - 1) : ' ';
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (prevChar != '\\' && nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
} else if (nextChar == '\\' && nextChar2 == '"') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else {
if (nextChar == ':') {
inValue = true;
b.append(nextChar);
} else if (nextChar == '[' || nextChar == '{') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '{' || nextChar == '}' || nextChar == ',') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
if (inValue) {
b.append("<span class='hlQuot'>"");
} else {
b.append("<span class='hlTagName'>"");
}
inQuote = true;
i += 5;
} else if (nextChar == ':') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = true;
} else {
b.append(nextChar);
}
}
}
} else {
boolean inQuote = false;
boolean inTag = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else if (inTag) {
if (nextChar == '&' && nextChar2 == 'g' && nextChar3 == 't' && nextChar4 == ';') {
b.append("</span><span class='hlControl'>></span>");
inTag = false;
i += 3;
} else if (nextChar == ' ') {
b.append("</span><span class='hlAttr'>");
b.append(nextChar);
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("<span class='hlQuot'>"");
inQuote = true;
i += 5;
} else {
b.append(nextChar);
}
} else {
if (nextChar == '&' && nextChar2 == 'l' && nextChar3 == 't' && nextChar4 == ';') {
b.append("<span class='hlControl'><</span><span class='hlTagName'>");
inTag = true;
i += 3;
} else {
b.append(nextChar);
}
}
}
}
return b.toString();
}
private String formatUrl(String theUrlBase, String theResultBody) {
String str = theResultBody;
if (str == null) {
return str;
}
try {
str = URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
ourLog.error("Should not happen", e);
}
StringBuilder b = new StringBuilder();
b.append("<span class='hlUrlBase'>");
boolean inParams = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
// char nextChar2 = i < str.length()-2 ? str.charAt(i+1):' ';
// char nextChar3 = i < str.length()-2 ? str.charAt(i+2):' ';
if (!inParams) {
if (nextChar == '?') {
inParams = true;
b.append("</span><wbr /><span class='hlControl'>?</span><span class='hlTagName'>");
} else {
if (i == theUrlBase.length()) {
b.append("</span><wbr /><span class='hlText'>");
}
b.append(nextChar);
}
} else {
if (nextChar == '&') {
b.append("</span><wbr /><span class='hlControl'>&</span><span class='hlTagName'>");
} else if (nextChar == '=') {
b.append("</span><span class='hlControl'>=</span><span class='hlAttr'>");
// }else if (nextChar=='%' && Character.isLetterOrDigit(nextChar2)&& Character.isLetterOrDigit(nextChar3)) {
// URLDecoder.decode(s, enc)
} else {
b.append(nextChar);
}
}
}
if (inParams) {
b.append("</span>");
}
return b.toString();
}
protected FhirContext getContext(HomeRequest theRequest) {
FhirVersionEnum version = theRequest.getFhirVersion(myConfig);
FhirContext retVal = myContexts.get(version);
if (retVal == null) {
retVal = newContext(version);
myContexts.put(version, retVal);
}
return retVal;
}
protected RuntimeResourceDefinition getResourceType(HomeRequest theRequest, HttpServletRequest theReq) throws ServletException {
String resourceName = StringUtils.defaultString(theReq.getParameter(PARAM_RESOURCE));
RuntimeResourceDefinition def = getContext(theRequest).getResourceDefinition(resourceName);
if (def == null) {
throw new ServletException("Invalid resourceName: " + resourceName);
}
return def;
}
protected ResultType handleClientException(GenericClient theClient, Exception e, ModelMap theModel) {
ResultType returnsResource;
returnsResource = ResultType.NONE;
ourLog.warn("Failed to invoke server", e);
if (e != null) {
theModel.put("errorMsg", toDisplayError("Error: " + e.getMessage(), e));
}
return returnsResource;
}
private IBaseResource loadAndAddConf(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
switch (theRequest.getFhirVersion(myConfig)) {
case DSTU2:
return loadAndAddConfDstu2(theServletRequest, theRequest, theModel);
case DSTU3:
return loadAndAddConfDstu3(theServletRequest, theRequest, theModel);
case R4:
return loadAndAddConfR4(theServletRequest, theRequest, theModel);
case DSTU2_1:
case DSTU2_HL7ORG:
break;
}
throw new IllegalStateException("Unknown version: " + theRequest.getFhirVersion(myConfig));
}
private IResource loadAndAddConfDstu2(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
ca.uhn.fhir.model.dstu2.resource.Conformance conformance;
try {
conformance = (ca.uhn.fhir.model.dstu2.resource.Conformance) client.fetchConformance().ofType(Conformance.class).execute();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement, error was: {}", e.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new ca.uhn.fhir.model.dstu2.resource.Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IBaseResource loadAndAddConfDstu3(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.dstu3.model.CapabilityStatement capabilityStatement = new CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.dstu3.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement, error was: {}", ex.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<CapabilityStatementRestResourceComponent>() {
@Override
public int compare(CapabilityStatementRestResourceComponent theO1, CapabilityStatementRestResourceComponent theO2) {
DecimalType count1 = new DecimalType();
List<Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalType) count1exts.get(0).getValue();
}
DecimalType count2 = new DecimalType();
List<Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
private IBaseResource loadAndAddConfR4(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.r4.model.CapabilityStatement capabilityStatement = new org.hl7.fhir.r4.model.CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.r4.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement, error was: {}", ex.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<org.hl7.fhir.r4.model.Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((org.hl7.fhir.r4.model.DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent>() {
@Override
public int compare(org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent theO1, org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementRestResourceComponent theO2) {
org.hl7.fhir.r4.model.DecimalType count1 = new org.hl7.fhir.r4.model.DecimalType();
List<org.hl7.fhir.r4.model.Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (org.hl7.fhir.r4.model.DecimalType) count1exts.get(0).getValue();
}
org.hl7.fhir.r4.model.DecimalType count2 = new org.hl7.fhir.r4.model.DecimalType();
List<org.hl7.fhir.r4.model.Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (org.hl7.fhir.r4.model.DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
protected String logPrefix(ModelMap theModel) {
return "[server=" + theModel.get("serverId") + "] - ";
}
protected FhirContext newContext(FhirVersionEnum version) {
FhirContext retVal;
retVal = new FhirContext(version);
return retVal;
}
private String parseNarrative(HomeRequest theRequest, EncodingEnum theCtEnum, String theResultBody) {
try {
IBaseResource par = theCtEnum.newParser(getContext(theRequest)).parseResource(theResultBody);
String retVal;
if (par instanceof IResource) {
IResource resource = (IResource) par;
retVal = resource.getText().getDiv().getValueAsString();
} else if (par instanceof IDomainResource) {
retVal = ((IDomainResource) par).getText().getDivAsString();
} else {
retVal = null;
}
return StringUtils.defaultString(retVal);
} catch (Exception e) {
ourLog.error("Failed to parse resource", e);
return "";
}
}
protected String preProcessMessageBody(String theBody) {
if (theBody == null) {
return "";
}
String retVal = theBody.trim();
StringBuilder b = new StringBuilder();
for (int i = 0; i < retVal.length(); i++) {
char nextChar = retVal.charAt(i);
int nextCharI = nextChar;
if (nextCharI == 65533) {
b.append(' ');
continue;
}
if (nextCharI == 160) {
b.append(' ');
continue;
}
if (nextCharI == 194) {
b.append(' ');
continue;
}
b.append(nextChar);
}
retVal = b.toString();
return retVal;
}
protected void processAndAddLastClientInvocation(GenericClient theClient, ResultType theResultType, ModelMap theModelMap, long theLatency, String outcomeDescription,
CaptureInterceptor theInterceptor, HomeRequest theRequest) {
try {
// ApacheHttpRequest lastRequest = theInterceptor.getLastRequest();
// HttpResponse lastResponse = theInterceptor.getLastResponse();
// String requestBody = null;
// String requestUrl = lastRequest != null ? lastRequest.getApacheRequest().getURI().toASCIIString() : null;
// String action = lastRequest != null ? lastRequest.getApacheRequest().getMethod() : null;
// String resultStatus = lastResponse != null ? lastResponse.getStatusLine().toString() : null;
// String resultBody = StringUtils.defaultString(theInterceptor.getLastResponseBody());
//
// if (lastRequest instanceof HttpEntityEnclosingRequest) {
// HttpEntity entity = ((HttpEntityEnclosingRequest) lastRequest).getEntity();
// if (entity.isRepeatable()) {
// requestBody = IOUtils.toString(entity.getContent());
// }
// }
//
// ContentType ct = lastResponse != null ? ContentType.get(lastResponse.getEntity()) : null;
// String mimeType = ct != null ? ct.getMimeType() : null;
IHttpRequest lastRequest = theInterceptor.getLastRequest();
IHttpResponse lastResponse = theInterceptor.getLastResponse();
String requestBody = null;
String requestUrl = null;
String action = null;
String resultStatus = null;
String resultBody = null;
String mimeType = null;
ContentType ct = null;
if (lastRequest != null) {
requestBody = lastRequest.getRequestBodyFromStream();
requestUrl = lastRequest.getUri();
action = lastRequest.getHttpVerbName();
}
if (lastResponse != null) {
resultStatus = "HTTP " + lastResponse.getStatus() + " " + lastResponse.getStatusInfo();
lastResponse.bufferEntity();
resultBody = IOUtils.toString(lastResponse.readEntity(), Constants.CHARSET_UTF8);
List<String> ctStrings = lastResponse.getHeaders(Constants.HEADER_CONTENT_TYPE);
if (ctStrings != null && ctStrings.isEmpty() == false) {
ct = ContentType.parse(ctStrings.get(0));
mimeType = ct.getMimeType();
}
}
EncodingEnum ctEnum = EncodingEnum.forContentType(mimeType);
String narrativeString = "";
StringBuilder resultDescription = new StringBuilder();
IBaseResource riBundle = null;
FhirContext context = getContext(theRequest);
if (ctEnum == null) {
resultDescription.append("Non-FHIR response");
} else {
switch (ctEnum) {
case JSON:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("JSON resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("JSON bundle");
riBundle = context.newJsonParser().parseResource(resultBody);
}
break;
case XML:
default:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("XML resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("XML bundle");
riBundle = context.newXmlParser().parseResource(resultBody);
}
break;
}
}
resultDescription.append(" (").append(defaultString(resultBody).length() + " bytes)");
Header[] requestHeaders = lastRequest != null ? applyHeaderFilters(lastRequest.getAllHeaders()) : new Header[0];
Header[] responseHeaders = lastResponse != null ? applyHeaderFilters(lastResponse.getAllHeaders()) : new Header[0];
theModelMap.put("outcomeDescription", outcomeDescription);
theModelMap.put("resultDescription", resultDescription.toString());
theModelMap.put("action", action);
theModelMap.put("ri", riBundle instanceof IAnyResource);
theModelMap.put("riBundle", riBundle);
theModelMap.put("resultStatus", resultStatus);
theModelMap.put("requestUrl", requestUrl);
theModelMap.put("requestUrlText", formatUrl(theClient.getUrlBase(), requestUrl));
String requestBodyText = format(requestBody, ctEnum);
theModelMap.put("requestBody", requestBodyText);
String resultBodyText = format(resultBody, ctEnum);
theModelMap.put("resultBody", resultBodyText);
theModelMap.put("resultBodyIsLong", resultBodyText.length() > 1000);
theModelMap.put("requestHeaders", requestHeaders);
theModelMap.put("responseHeaders", responseHeaders);
theModelMap.put("narrative", narrativeString);
theModelMap.put("latencyMs", theLatency);
} catch (Exception e) {
ourLog.error("Failure during processing", e);
theModelMap.put("errorMsg", toDisplayError("Error during processing: " + e.getMessage(), e));
}
}
/**
* A hook to be overridden by subclasses. The overriding method can modify the error message
* based on its content and/or the related exception.
*
* @param theErrorMsg The original error message to be displayed to the user.
* @param theException The exception that occurred. May be null.
* @return The modified error message to be displayed to the user.
*/
protected String toDisplayError(String theErrorMsg, Exception theException) {
return theErrorMsg;
}
protected enum ResultType {
BUNDLE, NONE, RESOURCE, TAGLIST
}
public static class CaptureInterceptor implements IClientInterceptor {
private IHttpRequest myLastRequest;
private IHttpResponse myLastResponse;
// private String myResponseBody;
public IHttpRequest getLastRequest() {
return myLastRequest;
}
public IHttpResponse getLastResponse() {
return myLastResponse;
}
// public String getLastResponseBody() {
// return myResponseBody;
// }
@Override
public void interceptRequest(IHttpRequest theRequest) {
assert myLastRequest == null;
myLastRequest = theRequest;
}
@Override
public void interceptResponse(IHttpResponse theResponse) throws IOException {
assert myLastResponse == null;
myLastResponse = theResponse;
// myLastResponse = ((ApacheHttpResponse) theResponse).getResponse();
//
// HttpEntity respEntity = myLastResponse.getEntity();
// if (respEntity != null) {
// final byte[] bytes;
// try {
// bytes = IOUtils.toByteArray(respEntity.getContent());
// } catch (IllegalStateException e) {
// throw new InternalErrorException(e);
// }
//
// myResponseBody = new String(bytes, "UTF-8");
// myLastResponse.setEntity(new MyEntityWrapper(respEntity, bytes));
// }
}
// private static class MyEntityWrapper extends HttpEntityWrapper {
//
// private byte[] myBytes;
//
// public MyEntityWrapper(HttpEntity theWrappedEntity, byte[] theBytes) {
// super(theWrappedEntity);
// myBytes = theBytes;
// }
//
// @Override
// public InputStream getContent() throws IOException {
// return new ByteArrayInputStream(myBytes);
// }
//
// @Override
// public void writeTo(OutputStream theOutstream) throws IOException {
// theOutstream.write(myBytes);
// }
//
// }
}
private static String sanitizeInput(String theString) {
String retVal = theString;
if (retVal != null) {
for (int i = 0; i < retVal.length(); i++) {
char nextChar = retVal.charAt(i);
switch (nextChar) {
case '\'':
case '"':
case '<':
case '>':
retVal = retVal.replace(nextChar, '_');
}
}
}
return retVal;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_883_0 |
crossvul-java_data_bad_24_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-79/java/bad_24_1 |
crossvul-java_data_bad_1165_0 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.context;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM;
import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.application.ResourceHandler;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.component.visit.VisitContextWrapper;
import javax.faces.component.visit.VisitHint;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;
import javax.faces.lifecycle.ClientWindow;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import com.sun.faces.component.visit.PartialVisitContext;
import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.HtmlUtils;
import com.sun.faces.util.Util;
public class PartialViewContextImpl extends PartialViewContext {
// Log instance for this class
private static Logger LOGGER = FacesLogger.CONTEXT.getLogger();
private boolean released;
// BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD
private PartialResponseWriter partialResponseWriter;
private List<String> executeIds;
private Collection<String> renderIds;
private List<String> evalScripts;
private Boolean ajaxRequest;
private Boolean partialRequest;
private Boolean renderAll;
private FacesContext ctx;
private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER";
// ----------------------------------------------------------- Constructors
public PartialViewContextImpl(FacesContext ctx) {
this.ctx = ctx;
}
// ---------------------------------------------- Methods from PartialViewContext
/**
* @see javax.faces.context.PartialViewContext#isAjaxRequest()
*/
@Override
public boolean isAjaxRequest() {
assertNotReleased();
if (ajaxRequest == null) {
ajaxRequest = "partial/ajax".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
if (!ajaxRequest) {
ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap().
get("Faces-Request"));
}
}
return ajaxRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isPartialRequest()
*/
@Override
public boolean isPartialRequest() {
assertNotReleased();
if (partialRequest == null) {
partialRequest = isAjaxRequest() ||
"partial/process".equals(ctx.
getExternalContext().getRequestHeaderMap().get("Faces-Request"));
}
return partialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#isExecuteAll()
*/
@Override
public boolean isExecuteAll() {
assertNotReleased();
String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx);
return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute));
}
/**
* @see javax.faces.context.PartialViewContext#isRenderAll()
*/
@Override
public boolean isRenderAll() {
assertNotReleased();
if (renderAll == null) {
String render = PARTIAL_RENDER_PARAM.getValue(ctx);
renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render));
}
return renderAll;
}
/**
* @see javax.faces.context.PartialViewContext#setRenderAll(boolean)
*/
@Override
public void setRenderAll(boolean renderAll) {
this.renderAll = renderAll;
}
@Override
public boolean isResetValues() {
Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx);
return (null != value && "true".equals(value)) ? true : false;
}
@Override
public void setPartialRequest(boolean isPartialRequest) {
this.partialRequest = isPartialRequest;
}
/**
* @see javax.faces.context.PartialViewContext#getExecuteIds()
*/
@Override
public Collection<String> getExecuteIds() {
assertNotReleased();
if (executeIds != null) {
return executeIds;
}
executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM);
// include the view parameter facet ID if there are other execute IDs
// to process
if (!executeIds.isEmpty()) {
UIViewRoot root = ctx.getViewRoot();
if (root.getFacetCount() > 0) {
if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) {
executeIds.add(0, UIViewRoot.METADATA_FACET_NAME);
}
}
}
return executeIds;
}
/**
* @see javax.faces.context.PartialViewContext#getRenderIds()
*/
@Override
public Collection<String> getRenderIds() {
assertNotReleased();
if (renderIds != null) {
return renderIds;
}
renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM);
return renderIds;
}
/**
* @see javax.faces.context.PartialViewContext#getEvalScripts()
*/
@Override
public List<String> getEvalScripts() {
assertNotReleased();
if (evalScripts == null) {
evalScripts = new ArrayList<>(1);
}
return evalScripts;
}
/**
* @see PartialViewContext#processPartial(javax.faces.event.PhaseId)
*/
@Override
public void processPartial(PhaseId phaseId) {
PartialViewContext pvc = ctx.getPartialViewContext();
Collection <String> myExecuteIds = pvc.getExecuteIds();
Collection <String> myRenderIds = pvc.getRenderIds();
UIViewRoot viewRoot = ctx.getViewRoot();
if (phaseId == PhaseId.APPLY_REQUEST_VALUES ||
phaseId == PhaseId.PROCESS_VALIDATIONS ||
phaseId == PhaseId.UPDATE_MODEL_VALUES) {
// Skip this processing if "none" is specified in the render list,
// or there were no execute phase client ids.
if (myExecuteIds == null || myExecuteIds.isEmpty()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"No execute and render identifiers specified. Skipping component processing.");
}
return;
}
try {
processComponents(viewRoot, phaseId, myExecuteIds, ctx);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO,
e.toString(),
e);
}
throw new FacesException(e);
}
// If we have just finished APPLY_REQUEST_VALUES phase, install the
// partial response writer. We want to make sure that any content
// or errors generated in the other phases are written using the
// partial response writer.
//
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ctx.setResponseWriter(writer);
}
} else if (phaseId == PhaseId.RENDER_RESPONSE) {
try {
//
// We re-enable response writing.
//
PartialResponseWriter writer = pvc.getPartialResponseWriter();
ResponseWriter orig = ctx.getResponseWriter();
ctx.getAttributes().put(ORIGINAL_WRITER, orig);
ctx.setResponseWriter(writer);
ExternalContext exContext = ctx.getExternalContext();
exContext.setResponseContentType("text/xml");
exContext.addResponseHeader("Cache-Control", "no-cache");
// String encoding = writer.getCharacterEncoding( );
// if( encoding == null ) {
// encoding = "UTF-8";
// }
// writer.writePreamble("<?xml version='1.0' encoding='" + encoding + "'?>\n");
writer.startDocument();
if (isResetValues()) {
viewRoot.resetValues(ctx, myRenderIds);
}
if (isRenderAll()) {
renderAll(ctx, viewRoot);
renderState(ctx);
writer.endDocument();
return;
}
renderComponentResources(ctx, viewRoot);
// Skip this processing if "none" is specified in the render list,
// or there were no render phase client ids.
if (myRenderIds != null && !myRenderIds.isEmpty()) {
processComponents(viewRoot, phaseId, myRenderIds, ctx);
}
renderState(ctx);
renderEvalScripts(ctx);
writer.endDocument();
} catch (IOException ex) {
this.cleanupAfterView();
} catch (RuntimeException ex) {
this.cleanupAfterView();
// Throw the exception
throw ex;
}
}
}
/**
* @see javax.faces.context.PartialViewContext#getPartialResponseWriter()
*/
@Override
public PartialResponseWriter getPartialResponseWriter() {
assertNotReleased();
if (partialResponseWriter == null) {
partialResponseWriter = new DelayedInitPartialResponseWriter(this);
}
return partialResponseWriter;
}
/**
* @see javax.faces.context.PartialViewContext#release()
*/
@Override
public void release() {
released = true;
ajaxRequest = null;
renderAll = null;
partialResponseWriter = null;
executeIds = null;
renderIds = null;
evalScripts = null;
ctx = null;
partialRequest = null;
}
// -------------------------------------------------------- Private Methods
private List<String> populatePhaseClientIds(PredefinedPostbackParameter parameterName) {
String param = parameterName.getValue(ctx);
if (param == null) {
return new ArrayList<>();
} else {
Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
String[] pcs = Util.split(appMap, param, "[ \t]+");
return ((pcs != null && pcs.length != 0)
? new ArrayList<>(Arrays.asList(pcs))
: new ArrayList<>());
}
}
// Process the components specified in the phaseClientIds list
private void processComponents(UIComponent component, PhaseId phaseId,
Collection<String> phaseClientIds, FacesContext context) throws IOException {
// We use the tree visitor mechanism to locate the components to
// process. Create our (partial) VisitContext and the
// VisitCallback that will be invoked for each component that
// is visited. Note that we use the SKIP_UNRENDERED hint as we
// only want to visit the rendered subtree.
EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE);
VisitContextFactory visitContextFactory = (VisitContextFactory)
FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY);
VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints);
PhaseAwareVisitCallback visitCallback =
new PhaseAwareVisitCallback(ctx, phaseId);
component.visitTree(visitContext, visitCallback);
PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext);
if (partialVisitContext != null) {
if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) {
Collection<String> unvisitedClientIds = partialVisitContext.getUnvisitedClientIds();
StringBuilder builder = new StringBuilder();
for (String cur : unvisitedClientIds) {
builder.append(cur).append(" ");
}
LOGGER.log(Level.FINER,
"jsf.context.partial_visit_context_unvisited_children",
new Object[]{builder.toString()});
}
}
}
/**
* Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s.
*
* If no {@link PartialVisitContext} is found in the chain, null is returned instead.
*
* @param visitContext the visit context.
* @return the (unwrapped) partial visit context.
*/
private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) {
if (visitContext == null) {
return null;
}
if (visitContext instanceof PartialVisitContext) {
return (PartialVisitContext) visitContext;
}
if (visitContext instanceof VisitContextWrapper) {
return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped());
}
return null;
}
private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException {
// If this is a "render all via ajax" request,
// make sure to wrap the entire page in a <render> elemnt
// with the special viewStateId of VIEW_ROOT_ID. This is how the client
// JavaScript knows how to replace the entire document with
// this response.
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
if (!(viewRoot instanceof NamingContainer)) {
writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
writer.endUpdate();
}
else {
/*
* If we have a portlet request, start rendering at the view root.
*/
writer.startUpdate(viewRoot.getClientId(context));
viewRoot.encodeBegin(context);
if (viewRoot.getChildCount() > 0) {
for (UIComponent uiComponent : viewRoot.getChildren()) {
uiComponent.encodeAll(context);
}
}
viewRoot.encodeEnd(context);
writer.endUpdate();
}
}
private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException {
ResourceHandler resourceHandler = context.getApplication().getResourceHandler();
PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
boolean updateStarted = false;
for (UIComponent resource : viewRoot.getComponentResources(context)) {
String name = (String) resource.getAttributes().get("name");
String library = (String) resource.getAttributes().get("library");
if (resource.getChildCount() == 0
&& resourceHandler.getRendererTypeForResourceName(name) != null
&& !resourceHandler.isResourceRendered(context, name, library))
{
if (!updateStarted) {
writer.startUpdate("javax.faces.Resource");
updateStarted = true;
}
resource.encodeAll(context);
}
}
if (updateStarted) {
writer.endUpdate();
}
}
private void renderState(FacesContext context) throws IOException {
// Get the view state and write it to the response..
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
String viewStateId = Util.getViewStateId(context);
writer.startUpdate(viewStateId);
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
writer.endUpdate();
ClientWindow window = context.getExternalContext().getClientWindow();
if (null != window) {
String clientWindowId = Util.getClientWindowId(context);
writer.startUpdate(clientWindowId);
writer.write(window.getId());
writer.endUpdate();
}
}
private void renderEvalScripts(FacesContext context) throws IOException {
PartialViewContext pvc = context.getPartialViewContext();
PartialResponseWriter writer = pvc.getPartialResponseWriter();
for (String evalScript : pvc.getEvalScripts()) {
writer.startEval();
writer.write(evalScript);
writer.endEval();
}
}
private PartialResponseWriter createPartialResponseWriter() {
ExternalContext extContext = ctx.getExternalContext();
String encoding = extContext.getRequestCharacterEncoding();
extContext.setResponseCharacterEncoding(encoding);
ResponseWriter responseWriter = null;
Writer out = null;
try {
out = extContext.getResponseOutputWriter();
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
}
if (out != null) {
UIViewRoot viewRoot = ctx.getViewRoot();
if (viewRoot != null) {
responseWriter =
ctx.getRenderKit().createResponseWriter(out,
"text/xml", encoding);
} else {
RenderKitFactory factory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT);
responseWriter = renderKit.createResponseWriter(out, "text/xml", encoding);
}
}
if (responseWriter instanceof PartialResponseWriter) {
return (PartialResponseWriter) responseWriter;
} else {
return new PartialResponseWriter(responseWriter);
}
}
private void cleanupAfterView() {
ResponseWriter orig = (ResponseWriter) ctx.getAttributes().
get(ORIGINAL_WRITER);
assert(null != orig);
// move aside the PartialResponseWriter
ctx.setResponseWriter(orig);
}
private void assertNotReleased() {
if (released) {
throw new IllegalStateException();
}
}
// ----------------------------------------------------------- Inner Classes
private static class PhaseAwareVisitCallback implements VisitCallback {
private PhaseId curPhase;
private FacesContext ctx;
private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) {
this.ctx = ctx;
this.curPhase = curPhase;
}
@Override
public VisitResult visit(VisitContext context, UIComponent comp) {
try {
if (curPhase == PhaseId.APPLY_REQUEST_VALUES) {
// RELEASE_PENDING handle immediate request(s)
// If the user requested an immediate request
// Make sure to set the immediate flag here.
comp.processDecodes(ctx);
} else if (curPhase == PhaseId.PROCESS_VALIDATIONS) {
comp.processValidators(ctx);
} else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) {
comp.processUpdates(ctx);
} else if (curPhase == PhaseId.RENDER_RESPONSE) {
PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter();
writer.startUpdate(comp.getClientId(ctx));
// do the default behavior...
comp.encodeAll(ctx);
writer.endUpdate();
} else {
throw new IllegalStateException("I18N: Unexpected " +
"PhaseId passed to " +
" PhaseAwareContextCallback: " +
curPhase.toString());
}
}
catch (IOException ex) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe(ex.toString());
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ex.toString(),
ex);
}
throw new FacesException(ex);
}
// Once we visit a component, there is no need to visit
// its children, since processDecodes/Validators/Updates and
// encodeAll() already traverse the subtree. We return
// VisitResult.REJECT to supress the subtree visit.
return VisitResult.REJECT;
}
}
/**
* Delays the actual construction of the PartialResponseWriter <em>until</em>
* content is going to actually be written.
*/
private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter {
private ResponseWriter writer;
private PartialViewContextImpl ctx;
// -------------------------------------------------------- Constructors
public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) {
super(null);
this.ctx = ctx;
ExternalContext extCtx = ctx.ctx.getExternalContext();
extCtx.setResponseContentType("text/xml");
extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding());
extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize());
}
// ---------------------------------- Methods from PartialResponseWriter
@Override
public void write(String text) throws IOException {
HtmlUtils.writeUnescapedTextForXML(getWrapped(), text);
}
@Override
public ResponseWriter getWrapped() {
if (writer == null) {
writer = ctx.createPartialResponseWriter();
}
return writer;
}
} // END DelayedInitPartialResponseWriter
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/bad_1165_0 |
crossvul-java_data_good_5810_0 | /*
* Copyright 2012 JBoss Inc
*
* 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 org.jbpm.console.ng.ht.client.editors.taskdetailsmulti;
import com.github.gwtbootstrap.client.ui.Heading;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.IsWidget;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.enterprise.event.Observes;
import org.jbpm.console.ng.ht.client.i18n.Constants;
import org.jbpm.console.ng.ht.model.events.TaskSelectionEvent;
import org.uberfire.client.annotations.DefaultPosition;
import org.uberfire.client.annotations.WorkbenchMenu;
import org.uberfire.lifecycle.OnOpen;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.AbstractWorkbenchScreenActivity;
import org.uberfire.client.mvp.Activity;
import org.uberfire.client.mvp.ActivityManager;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.mvp.UberView;
import org.uberfire.client.workbench.widgets.split.WorkbenchSplitLayoutPanel;
import org.uberfire.lifecycle.OnClose;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.security.Identity;
import org.uberfire.workbench.model.Position;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.Menus;
@Dependent
@WorkbenchScreen(identifier = "Task Details Multi")
public class TaskDetailsMultiPresenter {
private Constants constants = GWT.create(Constants.class);
@Inject
private ActivityManager activityManager;
@Inject
private PlaceManager placeManager;
private long selectedTaskId = 0;
private String selectedTaskName = "";
public interface TaskDetailsMultiView extends UberView<TaskDetailsMultiPresenter> {
void displayNotification(String text);
Heading getTaskIdAndName();
HTMLPanel getContent();
}
@Inject
Identity identity;
@Inject
public TaskDetailsMultiView view;
private Menus menus;
private PlaceRequest place;
private Map<String, AbstractWorkbenchScreenActivity> activitiesMap = new HashMap<String, AbstractWorkbenchScreenActivity>(4);
public TaskDetailsMultiPresenter() {
makeMenuBar();
}
@WorkbenchPartView
public UberView<TaskDetailsMultiPresenter> getView() {
return view;
}
@DefaultPosition
public Position getPosition(){
return Position.EAST;
}
@OnStartup
public void onStartup(final PlaceRequest place) {
this.place = place;
}
@WorkbenchPartTitle
public String getTitle() {
return constants.Details();
}
@OnOpen
public void onOpen() {
WorkbenchSplitLayoutPanel splitPanel = (WorkbenchSplitLayoutPanel)view.asWidget().getParent().getParent().getParent().getParent()
.getParent().getParent().getParent().getParent().getParent().getParent().getParent();
splitPanel.setWidgetMinSize(splitPanel.getWidget(0), 500);
}
public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){
selectedTaskId = event.getTaskId();
selectedTaskName = event.getTaskName();
view.getTaskIdAndName().setText(SafeHtmlUtils.htmlEscape(String.valueOf(selectedTaskId) + " - "+selectedTaskName));
view.getContent().clear();
String placeToGo;
if(event.getPlace() != null && !event.getPlace().equals("")){
placeToGo = event.getPlace();
}else{
placeToGo = "Task Details";
}
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
activitiesMap.put(placeToGo, activity);
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
}
@WorkbenchMenu
public Menus getMenus() {
return menus;
}
private void makeMenuBar() {
menus = MenuFactory
.newTopLevelMenu(constants.Work())
.respondsWith(new Command() {
@Override
public void execute() {
view.getContent().clear();
String placeToGo = "Form Display";
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
AbstractWorkbenchScreenActivity activity = null;
if(activitiesMap.get(placeToGo) == null){
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
}else{
activity = activitiesMap.get(placeToGo);
}
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
}
})
.endMenu()
.newTopLevelMenu(constants.Details())
.respondsWith(new Command() {
@Override
public void execute() {
view.getContent().clear();
String placeToGo = "Task Details";
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
AbstractWorkbenchScreenActivity activity = null;
if(activitiesMap.get(placeToGo) == null){
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
}else{
activity = activitiesMap.get(placeToGo);
}
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
}
})
.endMenu()
.newTopLevelMenu(constants.Assignments())
.respondsWith(new Command() {
@Override
public void execute() {
view.getContent().clear();
String placeToGo = "Task Assignments";
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
AbstractWorkbenchScreenActivity activity = null;
if(activitiesMap.get(placeToGo) == null){
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
}else{
activity = activitiesMap.get(placeToGo);
}
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
}
})
.endMenu()
.newTopLevelMenu(constants.Comments())
.respondsWith(new Command() {
@Override
public void execute() {
view.getContent().clear();
String placeToGo = "Task Comments";
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
AbstractWorkbenchScreenActivity activity = null;
if(activitiesMap.get(placeToGo) == null){
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
}else{
activity = activitiesMap.get(placeToGo);
}
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
}
})
.endMenu()
.build();
}
@OnClose
public void onClose(){
for(String activityId : activitiesMap.keySet()){
activitiesMap.get(activityId).onClose();
}
activitiesMap.clear();
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_5810_0 |
crossvul-java_data_good_3049_0 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts,
* Yahoo! Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.EnvVars;
import hudson.Util;
import hudson.model.queue.SubTask;
import hudson.scm.SCM;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.util.VariableResolver;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* A value for a parameter in a build.
*
* Created by {@link ParameterDefinition#createValue(StaplerRequest, JSONObject)} for
* a particular build (although this 'owner' build object is passed in for every method
* call as a parameter so that the parameter won't have to persist it.)
*
* <h2>Persistence</h2>
* <p>
* Instances of {@link ParameterValue}s are persisted into build's <tt>build.xml</tt>
* through XStream (via {@link ParametersAction}), so instances need to be persistable.
*
* <h2>Associated Views</h2>
* <h4>value.jelly</h4>
* The <tt>value.jelly</tt> view contributes a UI fragment to display the parameter
* values used for a build.
*
* <h2>Notes</h2>
* <ol>
* <li>{@link ParameterValue} is used to record values of the past build, but
* {@link ParameterDefinition} used back then might be gone already, or represent
* a different parameter now. So don't try to use the name to infer
* {@link ParameterDefinition} is.
* </ol>
* @see ParameterDefinition
* @see ParametersAction
*/
@ExportedBean(defaultVisibility=3)
public abstract class ParameterValue implements Serializable {
private static final Logger LOGGER = Logger.getLogger(ParameterValue.class.getName());
protected final String name;
private String description;
protected ParameterValue(String name, String description) {
this.name = name;
this.description = description;
}
protected ParameterValue(String name) {
this(name, null);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Restricted(DoNotUse.class) // for value.jelly
public String getFormattedDescription() {
try {
return Jenkins.getInstance().getMarkupFormatter().translate(description);
} catch (IOException e) {
LOGGER.warning("failed to translate description using configured markup formatter");
return "";
}
}
/**
* Name of the parameter.
*
* This uniquely distinguishes {@link ParameterValue} among other parameters
* for the same build. This must be the same as {@link ParameterDefinition#getName()}.
*/
@Exported
public final String getName() {
return name;
}
/**
* Adds environmental variables for the builds to the given map.
*
* <p>
* This provides a means for a parameter to pass the parameter
* values to the build to be performed.
*
* <p>
* When this method is invoked, the map already contains the
* current "planned export" list. The implementation is
* expected to add more values to this map (or do nothing)
*
* <p>
* <strike>Environment variables should be by convention all upper case.
* (This is so that a Windows/Unix heterogeneous environment
* won't get inconsistent result depending on which platform to
* execute.)</strike> (see {@link EnvVars} why upper casing is a bad idea.)
*
* @param env
* never null.
* @param build
* The build for which this parameter is being used. Never null.
* @deprecated as of 1.344
* Use {@link #buildEnvironment(Run, EnvVars)} instead.
*/
@Deprecated
public void buildEnvVars(AbstractBuild<?,?> build, Map<String,String> env) {
if (env instanceof EnvVars) {
if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvironment", Run.class, EnvVars.class)) {
// if the subtype already derives buildEnvironment, then delegate to it
buildEnvironment(build, (EnvVars) env);
} else if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvVars", AbstractBuild.class, EnvVars.class)) {
buildEnvVars(build, (EnvVars) env);
}
}
// otherwise no-op by default
}
/** @deprecated Use {@link #buildEnvironment(Run, EnvVars)} instead. */
@Deprecated
public void buildEnvVars(AbstractBuild<?,?> build, EnvVars env) {
if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvironment", Run.class, EnvVars.class)) {
buildEnvironment(build, env);
} else {
// for backward compatibility
buildEnvVars(build,(Map<String,String>)env);
}
}
/**
* Adds environmental variables for the builds to the given map.
*
* <p>
* This provides a means for a parameter to pass the parameter
* values to the build to be performed.
*
* <p>
* When this method is invoked, the map already contains the
* current "planned export" list. The implementation is
* expected to add more values to this map (or do nothing)
*
* @param env
* never null.
* @param build
* The build for which this parameter is being used. Never null.
* @since 1.556
*/
public void buildEnvironment(Run<?,?> build, EnvVars env) {
if (build instanceof AbstractBuild) {
buildEnvVars((AbstractBuild) build, env);
}
// else do not know how to do it
}
/**
* Called at the beginning of a build (but after {@link SCM} operations
* have taken place) to let a {@link ParameterValue} contributes a
* {@link BuildWrapper} to the build.
*
* <p>
* This provides a means for a parameter to perform more extensive
* set up / tear down during a build.
*
* @param build
* The build for which this parameter is being used. Never null.
* @return
* null if the parameter has no {@link BuildWrapper} to contribute to.
*/
public BuildWrapper createBuildWrapper(AbstractBuild<?,?> build) {
return null;
}
/**
* Returns a {@link VariableResolver} so that other components like {@link Builder}s
* can perform variable substitution to reflect parameter values into the build process.
*
* <p.
* This is yet another means in which a {@link ParameterValue} can influence
* a build.
*
* @param build
* The build for which this parameter is being used. Never null.
* @return
* if the parameter value is not interested in participating to the
* variable replacement process, return {@link VariableResolver#NONE}.
*/
public VariableResolver<String> createVariableResolver(AbstractBuild<?,?> build) {
return VariableResolver.NONE;
}
// TODO should there be a Run overload of this?
/**
* Accessing {@link ParameterDefinition} is not a good idea.
*
* @deprecated since 2008-09-20.
* parameter definition may change any time. So if you find yourself
* in need of accessing the information from {@link ParameterDefinition},
* instead copy them in {@link ParameterDefinition#createValue(StaplerRequest, JSONObject)}
* into {@link ParameterValue}.
*/
@Deprecated
public ParameterDefinition getDefinition() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParameterValue other = (ParameterValue) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/**
* Computes a human-readable possible-localized one-line description of the parameter value.
*
* <P>
* This message is used as a tooltip to describe jobs in the queue. The text should be one line without
* new line. No HTML allowed (the caller will perform necessary HTML escapes, so any text can be returend.)
*
* @since 1.323
*/
public String getShortDescription() {
return toString();
}
/**
* Returns whether the information contained in this ParameterValue is
* sensitive or security related. Used to determine whether the value
* provided by this object should be masked in output.
*
* <p>
* Subclasses can override this to control the return value.
*
* @since 1.378
*/
public boolean isSensitive() {
return false;
}
/**
* Returns the most natural Java object that represents the actual value, like
* boolean, string, etc.
*
* If there's nothing that really fits the bill, the callee can return {@code this}.
* @since 1.568
*/
public Object getValue() {
return null;
}
/**
* Controls where the build (that this parameter is submitted to) will happen.
*
* @return
* null to run the build where it normally runs. If non-null, this will
* override {@link AbstractProject#getAssignedLabel()}. If a build is
* submitted with multiple parameters, the first one that returns non-null
* from this method will win, and all others won't be consulted.
*
*
* @since 1.414
*/
public Label getAssignedLabel(SubTask task) {
return null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-79/java/good_3049_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.