code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
@XmlElementWrapper(name = "allpages")
@XmlElement(name = "p", type = P.class)
public List<P> getAllpages() {
return allpages;
} | java |
@XmlElementWrapper(name = "allimages")
@XmlElement(name = "img", type = Img.class)
public List<Img> getAllImages() {
return allimages;
} | java |
@XmlElementWrapper(name = "pages")
@XmlElement(name = "page", type = Page.class)
public List<Page> getPages() {
return pages;
} | java |
public void init() throws Exception {
// configure the SSLContext with a TrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
if (ignoreCertificates) {
ctx.init(new KeyManager[0],
new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
SSLContext.setDefault(ctx);... | java |
public void login() throws Exception {
WikiUser wuser = WikiUser.getUser(getWikiid(), getSiteurl());
if (wuser == null) {
throw new Exception(
"user for " + getWikiid() + "(" + getSiteurl() + ") not configured");
}
// wiki.setDebug(true);
try {
Login login = login(wuser.getUser... | java |
public Unmarshaller getUnmarshaller() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(classOfT);
Unmarshaller u = context.createUnmarshaller();
u.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent event) {
return true;... | java |
public T fromXML(String xml) throws Exception {
Unmarshaller u = this.getUnmarshaller();
u.setProperty(MarshallerProperties.MEDIA_TYPE, "application/xml");
T result = this.fromString(u, xml);
return result;
} | java |
public T fromJson(String json) throws Exception {
Unmarshaller u = this.getUnmarshaller();
u.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
T result = this.fromString(u, json);
return result;
} | java |
public String getString(Marshaller marshaller, T instance)
throws JAXBException {
StringWriter sw = new StringWriter();
marshaller.marshal(instance, sw);
String result = sw.toString();
return result;
} | java |
protected void initNameSpaces(General general, List<Ns> namespaceList) {
namespaces = new LinkedHashMap<String, Ns>();
namespacesById = new LinkedHashMap<Integer, Ns>();
namespacesByCanonicalName = new LinkedHashMap<String, Ns>();
for (Ns namespace : namespaceList) {
String namespacename = namespa... | java |
public String mapNamespace(String ns, SiteInfo targetWiki) throws Exception {
Map<String, Ns> sourceMap = this.getNamespaces();
Map<Integer, Ns> targetMap = targetWiki.getNamespacesById();
Ns sourceNs = sourceMap.get(ns);
if (sourceNs == null) {
if (debug)
LOGGER.log(Level.WARNING, "can no... | java |
public static String generateRandomKey(int pLength) {
int asciiFirst = 48;
int asciiLast = 122;
Integer[] exceptions = { 58,59,60,61,62,63,91,92,93,94,96 };
List<Integer> exceptionsList = Arrays.asList(exceptions);
SecureRandom random = new SecureRandom();
StringBuilder builder = new StringBuil... | java |
public static Crypt getRandomCrypt() {
String lCypher=generateRandomKey(32);
String lSalt=generateRandomKey(8);
Crypt result=new Crypt(lCypher,lSalt);
return result;
} | java |
String encrypt(String property) throws GeneralSecurityException,
UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(cypher));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pb... | java |
public static String getInput(String name, BufferedReader br)
throws IOException {
// prompt the user to enter the given name
System.out.print("Please Enter " + name + ": ");
String value = br.readLine();
return value;
} | java |
public static File getPropertyFile(String wikiId, String user) {
String userPropertiesFileName = System.getProperty("user.home")
+ "/.mediawiki-japi/" + user + "_" + wikiId + ".ini";
File propFile = new File(userPropertiesFileName);
return propFile;
} | java |
public static File getPropertyFile(String wikiId) {
String user = System.getProperty("user.name");
return getPropertyFile(wikiId, user);
} | java |
public static Properties getProperties(String wikiId)
throws FileNotFoundException, IOException {
File propFile = getPropertyFile(wikiId);
Properties props = new Properties();
props.load(new FileReader(propFile));
return props;
} | java |
public static WikiUser getUser(String wikiId, String siteurl) {
WikiUser result = null;
try {
Properties props = getProperties(wikiId);
result = new WikiUser();
result.setUsername(props.getProperty("user"));
result.setEmail(props.getProperty("email"));
Crypt pcf = new Crypt(props.... | java |
public static void createIniFile(String... args) {
try {
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String wikiid = null;
if (args.length > 0)
wikiid = args[0];
else
wikiid = getInput("wiki id", br);
String ... | java |
@XmlElementWrapper(name="modules")
@XmlElement(name="module", type=Module.class)
public List<Module> getModules() {
return modules;
} | java |
@XmlElementWrapper(name = "sections")
@XmlElement(name = "s", type = S.class)
public List<S> getSections() {
return sections;
} | java |
public static Api fromXML(final String xml) throws Exception {
Api result=null;
try {
result=apifactory.fromXML(xml);
} catch (JAXBException je) {
LOGGER.log(Level.SEVERE,je.getMessage());
LOGGER.log(Level.INFO,xml);
throw je;
}
return result;
} | java |
public String getIsoTimeStamp() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
} | java |
public static String getStringFromUrl(String urlString) {
ApacheHttpClient lclient = ApacheHttpClient.create();
WebResource webResource = lclient.resource(urlString);
ClientResponse response = webResource.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("HT... | java |
public Builder getResource(String queryUrl) throws Exception {
if (debug)
LOGGER.log(Level.INFO, queryUrl);
WebResource wrs = client.resource(queryUrl);
Builder result = wrs.header("USER-AGENT", USER_AGENT);
return result;
} | java |
public ClientResponse getPostResponse(String queryUrl, String params,
TokenResult token, Object pFormDataObject) throws Exception {
params = params.replace("|", "%7C");
params = params.replace("+", "%20");
// modal handling of post
FormDataMultiPart form = null;
MultivaluedMap<String, String... | java |
public ClientResponse getResponse(String url, Method method)
throws Exception {
Builder resource = getResource(url);
ClientResponse response = null;
switch (method) {
case Get:
response = resource.get(ClientResponse.class);
break;
case Post:
response = resource.post(ClientRes... | java |
public String getResponseString(ClientResponse response) throws Exception {
if (debug)
LOGGER.log(Level.INFO, "status: " + response.getStatus());
String responseText = response.getEntity(String.class);
if (response.getStatus() != 200) {
handleError("status " + response.getStatus() + ":'" + respo... | java |
public Map<String, String> getParamMap(String params) {
Map<String, String> result = new HashMap<String, String>();
String[] paramlist = params.split("&");
for (int i = 0; i < paramlist.length; i++) {
String[] parts = paramlist[i].split("=");
if (parts.length == 2)
result.put(parts[0], p... | java |
public String getActionResultText(String action, String params,
TokenResult token, Object pFormData, String format) throws Exception {
String queryUrl = siteurl + scriptPath + apiPath + "action=" + action
+ "&format=" + format;
ClientResponse response;
// decide for the method to use for api a... | java |
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData, String format) throws Exception {
String text = this.getActionResultText(action, params, token, pFormData,
format);
Api api = null;
if ("xml".equals(format)) {
if (debug) {
// convert th... | java |
public Api getActionResult(String action, String params, TokenResult token,
Object pFormData) throws Exception {
return getActionResult(action, params, token, pFormData, format);
} | java |
public Api getActionResult(String action, String params) throws Exception {
Api result = this.getActionResult(action, params, null, null);
return result;
} | java |
public Api getQueryResult(String query) throws Exception {
Api result = this.getActionResult("query", query, null, null);
return result;
} | java |
public TokenResult prepareLogin(String username) throws Exception {
username = encode(username);
Api apiResult = null;
TokenResult token = new TokenResult();
token.tokenName = "lgtoken";
token.tokenMode = TokenMode.token1_19;
// see https://github.com/WolfgangFahl/Mediawiki-Japi/issues/31
if... | java |
public Login login(String username, String password, String domain)
throws Exception {
// login is a two step process
// first we get a token
TokenResult token = prepareLogin(username);
// and then with the token we login using the password
Login login = login(token, username, password, domain... | java |
public Login login(String username, String password) throws Exception {
return login(username, password, null);
} | java |
public void logout() throws Exception {
Api apiResult = getActionResult("logout", "", null, null);
if (apiResult != null) {
userid = null;
// FIXME check apiResult
}
if (cookies != null) {
cookies.clear();
cookies = null;
}
} | java |
public String getSectionText(String pageTitle, int sectionNumber)
throws Exception {
String result = this.getPageContent(pageTitle,
"&rvsection=" + sectionNumber, false);
return result;
} | java |
public Parse getParse(String params) throws Exception {
String action = "parse";
Api api = getActionResult(action, params);
super.handleError(api);
return api.getParse();
} | java |
public synchronized void upload(InputStream fileToUpload, String filename,
String contents, String comment) throws Exception {
TokenResult token = getEditToken("File:" + filename, "edit");
final FormDataMultiPart multiPart = new FormDataMultiPart();
// http://stackoverflow.com/questions/5772225/trying... | java |
public static void showVersion() {
System.err.println("Mediawiki-Japi Version: " + VERSION);
System.err.println();
System.err
.println(" github: https://github.com/WolfgangFahl/Mediawiki-Japi");
System.err.println("");
} | java |
public void usage(String msg) {
System.err.println(msg);
showVersion();
System.err.println(" usage: java com.bitplan.mediawiki.japi.Mediawiki");
parser.printUsage(System.err);
exitCode = 1;
} | java |
public Api createAccount(String name, String eMail, String realname,
boolean mailpassword, String reason, String language) throws Exception {
String createtoken="?";
if (getVersion().compareToIgnoreCase("Mediawiki 1.27") >= 0) {
Api apiResult = this.getQueryResult("&meta=tokens&type=createaccount");... | java |
public List<Rc> sortByTitleAndFilterDoubles(List<Rc> rcList) {
List<Rc> result = new ArrayList<Rc>();
List<Rc> sorted = new ArrayList<Rc>();
sorted.addAll(rcList);
Collections.sort(sorted, new Comparator<Rc>() {
@Override
public int compare(Rc lRc, Rc rRc) {
int result = lRc.getTitle... | java |
public String dateToMWTimeStamp(Date date) {
SimpleDateFormat mwTimeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String result = mwTimeStampFormat.format(date);
return result;
} | java |
public List<Rc> getMostRecentChanges(int days, int rcLimit) throws Exception {
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -days);
Date date30daysbefore = cal.getTime();
String rcstart = dateToMWTimeStamp(today);
String ... | java |
protected void handleError(String errMsg) throws Exception {
// log it
LOGGER.log(Level.SEVERE, errMsg);
// and throw an error if this is configured
if (this.isThrowExceptionOnError()) {
throw new Exception(errMsg);
}
} | java |
protected void handleError(Error error) throws Exception {
String errMsg="error: "+error.getCode()+" info: "+error.getInfo();
handleError(errMsg);
} | java |
public Api fromXML(String xml) throws Exception {
// retrieve the JAXB wrapper representation from the xml received
Api api = Api.fromXML(xml);
// check whether an error code was sent
Error error = api.getError();
// if there is an error - handle it
if (error != null) {
// prepare the erro... | java |
protected String encode(String param) throws Exception {
String result = URLEncoder.encode(param, "UTF-8");
return result;
} | java |
protected String decode(String html) throws Exception {
String result=StringEscapeUtils.unescapeHtml4(html);
return result;
} | java |
public String normalizeTitle(String title) throws Exception {
String result = encode(title);
result=result.replace("+","_");
return result;
} | java |
public static AccessContext getAccessContextOnThread() {
final Stack<AccessContext> stack = threadLocal.get();
return stack != null ? stack.peek() : null;
} | java |
public static void setAccessContextOnThread(AccessContext accessContext) {
if (accessContext == null) {
String msg = "The argument[accessContext] must not be null.";
throw new IllegalArgumentException(msg);
}
Stack<AccessContext> stack = threadLocal.get();
if (sta... | java |
public static boolean isExistAccessContextOnThread() {
final Stack<AccessContext> stack = threadLocal.get();
return stack != null ? !stack.isEmpty() : false;
} | java |
public void downloadStreamCall(ResponseDownloadResource resource, HttpServletResponse response) {
final WrittenStreamCall streamCall = resource.getStreamCall();
if (streamCall == null) {
String msg = "Either byte data or input stream is required: " + resource;
throw new IllegalAr... | java |
public static Date getTransactionTime() {
final Stack<Date> stack = threadLocal.get();
return stack != null ? stack.peek() : null;
} | java |
public static void setTransactionTime(Date transactionTime) {
if (transactionTime == null) {
String msg = "The argument 'transactionTime' should not be null.";
throw new IllegalArgumentException(msg);
}
Stack<Date> stack = threadLocal.get();
if (stack == null) {
... | java |
public ActionExecute findActionExecute(String paramPath) { // null allowed when not found
for (ActionExecute execute : executeMap.values()) {
if (execute.determineTargetByPathParameter(paramPath)) {
return execute;
}
}
return null;
} | java |
protected void doSetFrom(String from, String personal) {
assertArgumentNotEmpty("from", from);
assertArgumentNotEmpty("personal", personal); // only from required
postcard.setFrom(createAddress(from, personal));
} | java |
public void pushLogging(String key, Object value) {
assertArgumentNotNull("key", key);
assertArgumentNotNull("value", value);
postcard.pushLogging(key, value);
} | java |
protected List<Class<? extends Annotation>> createAnnotationTypeList(Class<?>... annotations) {
final List<Class<? extends Annotation>> annotationList = new ArrayList<Class<? extends Annotation>>();
for (Class<?> annoType : annotations) {
@SuppressWarnings("unchecked")
final Clas... | java |
protected SqlStringFilter createSqlStringFilter(ActionRuntime runtime) {
final Method actionMethod = runtime.getExecuteMethod();
return newRomanticTraceableSqlStringFilter(actionMethod, () -> {
return buildSqlMarkingAdditionalInfo(); // lazy because it may be auto-login later
});
... | java |
protected void checkLoginRequired(ActionRuntime runtime) throws LoginRequiredException {
loginManager.ifPresent(nager -> {
nager.checkLoginRequired(createLogingHandlingResource(runtime));
});
} | java |
public void setWrappedData(Object data) {
if (data == null) {
inner = null;
arrayFromInner = null;
setRowIndex(-1);
} else {
inner = (Collection<E>) data;
arrayFromInner = (E[]) new Object[inner.size()];
inner.toArray(ar... | java |
protected SqlAnalyzer createSqlAnalyzer(String templateText, boolean blockNullParameter) {
final SqlAnalyzer analyzer = new SqlAnalyzer(templateText, blockNullParameter) {
@Override
protected String filterAtFirst(String sql) {
return sql; // keep body
}
... | java |
@Override
public OptionalEntity<USER_ENTITY> findLoginUser(Object userId) {
assertUserIdRequired(userId);
try {
@SuppressWarnings("unchecked")
final ID castId = (ID) userId;
return doFindLoginUser(castId);
} catch (ClassCastException e) { // also find meth... | java |
protected void doLogin(LoginCredential credential, LoginSpecifiedOption option) throws LoginFailureException {
handleLoginSuccess(findLoginUser(credential).orElseThrow(() -> {
final String msg = "Not found the user by the credential: " + credential + ", " + option;
return handleLoginFail... | java |
protected void handleLoginSuccess(USER_ENTITY userEntity, LoginSpecifiedOption option) {
assertUserEntityRequired(userEntity);
final USER_BEAN userBean = saveLoginInfoToSession(userEntity);
if (userBean instanceof SyncCheckable) {
((SyncCheckable) userBean).manageLastestSyncCheckTime... | java |
protected USER_BEAN saveLoginInfoToSession(USER_ENTITY userEntity) {
regenerateSessionId();
logger.debug("...Saving login info to session");
final USER_BEAN userBean = createUserBean(userEntity);
sessionManager.setAttribute(getUserBeanKey(), userBean);
return userBean;
} | java |
protected void saveRememberMeKeyToCookie(USER_ENTITY userEntity, USER_BEAN userBean) {
final int expireDays = getRememberMeAccessTokenExpireDays();
getCookieRememberMeKey().ifPresent(cookieKey -> {
doSaveRememberMeCookie(userEntity, userBean, expireDays, cookieKey);
});
} | java |
protected void doSaveRememberMeCookie(USER_ENTITY userEntity, USER_BEAN userBean, int expireDays, String cookieKey) {
logger.debug("...Saving remember-me key to cookie: key={}", cookieKey);
final String value = buildRememberMeCookieValue(userEntity, userBean, expireDays);
final int expireSeconds... | java |
protected boolean isValidRememberMeCookie(String userKey, String expireDate) {
final String currentDate = formatForRememberMeExpireDate(timeManager.currentHandyDate());
if (currentDate.compareTo(expireDate) < 0) { // String v.s. String
return true; // valid access token within time limit
... | java |
protected boolean doRememberMe(ID userId, String expireDate, RememberMeLoginSpecifiedOption option) {
final boolean updateToken = option.isUpdateToken();
final boolean silentLogin = option.isSilentLogin();
if (logger.isDebugEnabled()) {
final StringBuilder sb = new StringBuilder();
... | java |
protected void asLoginRequired(LoginHandlingResource resource) throws LoginRequiredException {
logger.debug("...Checking login status for login required");
if (tryAlreadyLoginOrRememberMe(resource)) {
checkPermission(resource); // throws if denied
return; // Good
}
... | java |
protected void asNonLoginRequired(LoginHandlingResource resource) throws LoginRequiredException {
if (!isSuppressRememberMeOfNonLoginRequired(resource)) { // option just in case
logger.debug("...Checking login status for non login required");
if (tryAlreadyLoginOrRememberMe(resource)) {
... | java |
public Object remove(Serializable key) {
if(component.initialStateMarked()) {
Object retVal = deltaMap.remove(key);
if(retVal==null) {
return defaultMap.remove(key);
}
else {
defaultMap.remove(key);
return retVal;
... | java |
public Object saveState(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if(component.initialStateMarked()) {
return saveMap(context, deltaMap);
}
else {
return saveMap(context, defaultMap);
}
} | java |
public void restoreState(FacesContext context, Object state) {
if (context == null) {
throw new NullPointerException();
}
if (state == null) {
return;
}
if (!component.initialStateMarked() && !defaultMap.isEmpty())
{
defaultMa... | java |
private void advance() {
try {
if (tok == null)
tok = source.token();
} catch (LexerException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} | java |
@Override
public Token next() {
if (!hasNext())
throw new NoSuchElementException();
Token t = this.tok;
this.tok = null;
return t;
} | java |
private static Object saveBindings(FacesContext context,
Map<String, ValueExpression> bindings) {
// Note: This code is copied from UIComponentBase. In a future
// version of the JSF spec, it would be useful to define a
// attribute/property/bindings/stat... | java |
private static Map<String, ValueExpression> restoreBindings(FacesContext context,
Object state) {
// Note: This code is copied from UIComponentBase. See note above
// in saveBindings().
if (state == null) {
return (nu... | java |
private void setLiteralValue(String propertyName,
ValueExpression expression) {
assert(expression.isLiteralText());
Object value;
ELContext context = FacesContext.getCurrentInstance().getELContext();
try {
value = expression.getValue(contex... | java |
private static List<String> toSingletonList(String propertyName,
String value) {
if ((null == value) || (value.length() == 0)) {
return null;
}
if (value.charAt(0) == '@') {
// These are very common, so we use shared copies
... | java |
private static Object[] toObjectArray(Object primitiveArray) {
if (primitiveArray == null) {
throw new NullPointerException();
}
if (primitiveArray instanceof Object[]) {
return (Object[]) primitiveArray;
}
if (primitiveArray instanceof Collectio... | java |
public boolean hasMessageOf(String property) {
assertArgumentNotNull("property", property);
final UserMessageItem item = getPropertyItem(property);
return item != null && !item.getMessageList().isEmpty();
} | java |
public boolean hasMessageOf(String property, String messageKey) {
assertArgumentNotNull("property", property);
assertArgumentNotNull("messageKey", messageKey);
final UserMessageItem item = getPropertyItem(property);
return item != null && item.getMessageList().stream().anyMatch(message -... | java |
private static int _indexOfStartingFrom(List<?> list, int startIndex, Object searchValue)
{
int itemCount = list.size();
boolean found = false;
// start searching from location remembered from last time
for (int currIndex = startIndex; currIndex < itemCount; currIndex++)
{
... | java |
private Resource findComponentResourceBundleLocaleMatch(FacesContext context,
String resourceName, String libraryName) {
Resource result = null;
ResourceBundle resourceBundle = null;
int i;
if (-1 != (i = resourceName.lastIndexOf("."))) {
resourceName = resourceN... | java |
private void clearFacesEvents(FacesContext context) {
if (context.getRenderResponse() || context.getResponseComplete()) {
if (events != null) {
for (List<FacesEvent> eventList : events) {
if (eventList != null) {
eventList.clear();
... | java |
private static Locale getLocaleFromString(String localeStr)
throws IllegalArgumentException {
// length must be at least 2.
if (null == localeStr || localeStr.length() < 2) {
throw new IllegalArgumentException("Illegal locale String: " +
... | java |
protected String convertToPerformanceView(long afterMinusBefore) { // from DfTraceViewUtil.java
if (afterMinusBefore < 0) {
return String.valueOf(afterMinusBefore);
}
long sec = afterMinusBefore / 1000;
final long min = sec / 60;
sec = sec % 60;
final long mi... | java |
protected List<Object> resolveLabelParameter(Locale locale, String key, Object[] args) {
final MessageResourceBundle bundle = getBundle(locale);
if (args == null || args.length == 0) {
return DfCollectionUtil.emptyList();
}
final List<Object> resolvedList = new ArrayList<Obje... | java |
@Override
public void handleWarning(Source source, int line, int column,
String msg)
throws LexerException {
warnings++;
print(source.getName() + ":" + line + ":" + column
+ ": warning: " + msg);
} | java |
@Override
public void handleError(Source source, int line, int column,
String msg)
throws LexerException {
errors++;
print(source.getName() + ":" + line + ":" + column
+ ": error: " + msg);
} | java |
protected OptionalThing<ClassificationMeta> findMeta(Class<?> defmetaType, String classificationName) {
return LaClassificationUtil.findMeta(defmetaType, classificationName);
} | java |
private void executeValidate(FacesContext context) {
try {
validate(context);
} catch (RuntimeException e) {
context.renderResponse();
throw e;
}
if (!isValid()) {
context.validationFailed();
context.renderResponse();
}... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.